Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Help parsing JSON in java

Tags:

java

json

Would it be possible if someone could help me parse this json result. I have retrieved the result as a string

{"query":{"latitude":39.9889,"longitude":-82.8118},"timestamp":1310252291.861,"address":{"geometry":{"coordinates":[-82.81168367358264,39.9887910986731],"type":"Point"},"properties":{"address":"284 Macdougal Ln","distance":"0.02","postcode":"43004","city":"Columbus","county":"Franklin","province":"OH","country":"US"},"type":"Feature"}}
like image 715
Brandon Wilson Avatar asked Dec 09 '22 07:12

Brandon Wilson


1 Answers

Jackson. Simple and intuitive to use. For me the best available. Start out with Simple Data Binding, it will throw everything it finds in Maps and Lists.

Like this:

ObjectMapper mapper = new ObjectMapper();
Map<String,Object> yourData = mapper.readValue(new File("yourdata.json"), Map.class);

That's all that's needed.

A good and quick introduction can be found here

And a full working example with your actual data:

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

public class Main {

    public static void main(String[] args) throws IOException {
        ObjectMapper mapper = new ObjectMapper();
        Map<?,?> rootAsMap = mapper.readValue(
                "{\"query\":{\"latitude\":39.9889,\"longitude\":-82.8118},\"timestamp\":1310252291.861,\"address\":{\"geometry\":{\"coordinates\":[-82.81168367358264,39.9887910986731],\"type\":\"Point\"},\"properties\":{\"address\":\"284 Macdougal Ln\",\"distance\":\"0.02\",\"postcode\":\"43004\",\"city\":\"Columbus\",\"county\":\"Franklin\",\"province\":\"OH\",\"country\":\"US\"},\"type\":\"Feature\"}}".getBytes(),
                Map.class);
        System.out.println(rootAsMap);
        Map query = (Map) rootAsMap.get("query");
        Map address = (Map) rootAsMap.get("address");
        Map addressProperties = (Map) address.get("properties");
        String county = (String) addressProperties.get("county");
        System.out.println("County is " + county);
    }

}

Now, this whole Map juggling also illustrates Bozho's point pretty well, using full binding (by creating a Java class that reflects the content of the JSON data) will work better in the end.

like image 160
fvu Avatar answered Dec 29 '22 05:12

fvu