1

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.

6
  • post your full string which u want to convert in json object Commented Dec 7, 2012 at 22:26
  • Which JSONObject have you imported? Commented Dec 7, 2012 at 22:27
  • are sure that the string begins with square bracket ? Commented Dec 7, 2012 at 22:27
  • @JonathanGarcía that just means the object is an array, which is valid JSON AFAIK. Commented Dec 7, 2012 at 22:30
  • 1
    Then i believe that should use JSONArray, JSONObject of instead Commented Dec 7, 2012 at 22:39

3 Answers 3

1

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

Sign up to request clarification or add additional context in comments.

Comments

0

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);

Comments

0
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, ...
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.