简体   繁体   中英

In Java, how to convert a String to JSON Object?

The string is like so:

[{"Id":287,"Name":"aaaaaaaa","ProjectType":"GP"}, ... snip ...]

This STRING is not JSON yet since it is a string even though it was served up as JSON.

I am trying to convert that to a structure that I can work with in my Java app.

Can somebody help me out here. The examples I've found so far didn't work out for me. Basically, I was hoping to be able to iterate over the Dictionaries that are within the List.

My latest attempt to convert the string into a json, was this:

JSONObject data = new JSONObject(json_string);

This, however, returned null .

Thank you.

look at using the Gson Lib - it's very good at handling this sort of thing. If you implement it using generics you can create a set of serializers which would let you import data very nicely from mobile APIs. If you want more info on example implementations let me know

Source: http://code.google.com/p/google-gson/

documentation: https://sites.google.com/site/gson/gson-user-guide

To go along with the Gson answer, I would suggest jackson . In my experience it's faster and just as easy to use.

ObjectMapper mapper = new ObjectMapper(); // can reuse, share globally
Map<String, Object> myMap = mapper.readValue(myJSONString, Map.class);

In your case, where the JSON is a list (I'm not sure if that's legal as the "root" element) you'd need to do List<Map<String, Object>> myList = mapper.readValue(myJSONString, List.class);

import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

JsonElement json = new JsonParser().parse("[{\"Id\":287,\"Name\":\"aaaaaaaa\",\"ProjectType\":\"GP\"}]");
        if(json.isJsonArray()) {        
            for(JsonElement elem : json.getAsJsonArray()) {
                //elem.getAsJsonObject().get("Id")
            }
        } else if (json.isJsonObject()) {
            //json.getAsJsonObject()
        } //other else cases for JsonNull, ...
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM