2

I have something like the following json string:

{"values" : [
           { "group":"A"
             "rating":2
           },
           {
             "group":"B"
             "language":"english"
           }
         ]
}

As you can see, "values" is an array, with different type of objects. One type can contain a string and an integer, and the other type contains a string and another string.

How do I deal with this?

Karan
  • 11,509
  • 8
  • 34
  • 38
  • If I put the second variable as an integer, it gives an error while parsing the "group B" type of object, even though i'm "using" only "group A" type objects (i.e., I only use the first element of this array). I'm fully certain that the first element always has groupA elements, but I guess it has to parse all the elements. – Karan Jun 24 '11 at 04:31

3 Answers3

0

Sorry, I didn't notice originally you wrote "gson". I'm not sure you can do it, and here's not me saying it.

Amadan
  • 191,408
  • 23
  • 240
  • 301
  • Apparently you can : http://code.google.com/p/google-gson/source/browse/trunk/extras/src/main/java/com/google/gson/extras/examples/rawcollections/RawCollectionsExample.java – Karan Jun 24 '11 at 05:05
  • RawCollectionsExample is not an example of polymorphic deserialization, which is how I'd preferably approach this. – Programmer Bruce Jun 24 '11 at 08:28
0

Do some thing like the following

List myStrings = new ArrayList();
    myStrings = gson.fromJson(json,myStrings.getClass());

    Iterator myIterator = myStrings.iterator();
    boolean b;
    while(myIterator.hasNext()){
        Object o =myIterator.next();
        b=o instanceof String;

        System.out.println("...."+b);
    }
Sunil Kumar Sahoo
  • 53,011
  • 55
  • 178
  • 243
0

My approach would probably be to implement a polymorphic deserialization solution.

Gson does not currently have a simple mechanism for polymorphic deserialization, other than implementing custom deserialization processing. The next release looks like it will provide a built-in solution.

Previous StackOverflow.com Questions And Answers (Some With Examples) On This Topic:

Specific to the original question, it looks like the "group" element would be used to distinguish between different types.

FWIW, Jackson released a built-in solution to this problem many moons ago.

Community
  • 1
  • 1
Programmer Bruce
  • 64,977
  • 7
  • 99
  • 97