Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java JSON -Jackson- Nested Elements

Tags:

java

json

jackson

My JSON string has nested values.

Something like

"[{"listed_count":1720,"status":{"retweet_count":78}}]"

I want the value of the retweet_count.

I'm using Jackson.

The code below outputs "{retweet_count=78}" and not 78. I'm wondering if I can get nested values the kind of way PHP does it i.e status->retweet_count. Thanks.

import java.io.IOException;
import java.util.List;
import java.util.Map;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.TypeReference;

public class tests {
public static void main(String [] args) throws IOException{
    ObjectMapper mapper = new ObjectMapper();
  List <Map<String, Object>> fwers = mapper.readValue("[{\"listed_count\":1720,\"status\":{\"retweet_count\":78}}]]", new TypeReference<List <Map<String, Object>>>() {});
    System.out.println(fwers.get(0).get("status"));

    }
}
like image 393
Mob Avatar asked Dec 05 '11 16:12

Mob


1 Answers

If you know the basic structure of the data you're retrieving, it makes sense to represent it properly. You get all sorts of niceties like type safety ;)

public static class TweetThingy {
    public int listed_count;
    public Status status;

    public static class Status {
        public int retweet_count;
    }
}

List<TweetThingy> tt = mapper.readValue(..., new TypeReference<List<TweetThingy>>() {});
System.out.println(tt.get(0).status.retweet_count);
like image 67
ptomli Avatar answered Oct 19 '22 23:10

ptomli