0

My JSON object looks something like this:

{
    id: 1
    object:
        {
            object_id:1
            key_for_1: "value for object type 1"
        }
    type: "object_type_1"
 }

{
    id: 2
    object:
        {
            object_id:5
            key_for_23: "value for object type 23"
        }
    type: "object_type_23"
 }

So, basically i need "type" before i can parse object. Is there a way to ensure that I can grab the value for "type" before i grab "object"?

JsonReader is has pretty much the same methods as GSON. Here is how I am parsing it:

public CustomObject(JsonReader reader) throws IOException {
    reader.beginObject();
    while (reader.hasNext()) {

        String name = reader.nextName();

        if (name.equals("id")) {
            clId = reader.nextDouble();
        } 

        else if (name.equals("object")) {
            innerObject = new InnerObject(reader);
        }

        else if (name.equals("type")) {
            type = reader.nextString();
        }
    }

    reader.endObject();
}

I don't want to just use a string builder because the actual JSON object I get back is HUGE (the one above is just a sample). I tried StringBuilder first and I am seeing quite a few out of memory problems which is why I wanted to move to JsonReader.

Any help would be awesome. Thanks

Sree
  • 2,727
  • 3
  • 29
  • 47

1 Answers1

1

First of all to simplify parsing JSON object, you can use org.json library. Secondly, I think this is an invalid JSON object structure.

Do you intend to have an array of JSON objects with each item (Data in this case) having following name:value pairs?

{ "Data": [ id: 1 object: { object_id:5 key_for_23: "value for object type 23" } type: "object_type_23" },{ }]

{

}

Komal Gupta
  • 1,682
  • 2
  • 15
  • 18
  • yea, sorry the structure isn't perfect. i just wanted to give an example. Basically, i am given an array of json objects and each of them has 3 keys (the ones above). To use org.json I need to convert the Json to a string which i wanted to avoid – Sree Jul 28 '15 at 17:31
  • When you say you need to convert it to string, what exactly does that imply? Because a JSON object can have different key- value pairs, with values being String, integer, boolean etc. E.g. { "Amount": 100.50, "age":30, "is_adult":true, "name":"foo" } For your array of Json objects, would there be object_id for each element of jsonArray object. Because I see 2 ids. If you could give an example of one valid Json object with elements in case then I would be able to hep with the parsing. – Komal Gupta Jul 29 '15 at 17:54
  • So basically I grab the output from the HTTPUrlConnection (which is json) and build it using a string builder. Then I feed the string into a JSONObject. JSONObject fetchedNewsFeedObjects = new JSONObject(sb.toString()); So, I am "converting" the JSON into a string so i can feed it into the JSONObject object. Did that make sense? – Sree Jul 29 '15 at 20:52