开发者

Parsing an object with variable type in gson

开发者 https://www.devze.com 2023-03-15 06:25 出处:网络
I have something like the following json string: {\"values\" : [ { \"group\":\"A\" \"rating\":2 }, { \"group\":\"B\"

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 typ开发者_开发技巧e contains a string and another string.

How do I deal with this?


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


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


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:

  • Deserialising a generic with unknown compile time type where a field indicates the type
  • Parse JSON with no specific structure for a field with GSON
  • json object serialization/deserialization using google gson
  • Polymorphism with gson

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消