How can I deserialize an array inside a JSON object?

前端 未结 2 1009
遥遥无期
遥遥无期 2020-12-21 12:35

I can\'t work out how to deserialize an array inside a JSON object using Gson. The json object that i\'m trying to deserialize looks like this:

{\"item0\":3         


        
2条回答
  •  太阳男子
    2020-12-21 12:57

    There's a couple of problems here:

    One, I don't think you're using the array like you think you are. You have "arrayItem1" through 3, but they are contained in a single JSON object within the array... so the array actually only has one item.

    The array should probably be something like:

    "array": [
      321779321,
      "asdfafd",
      "asasdfadf"
    ]
    

    The second is that the type of array in your Java class is Object... that doesn't give Gson any type information to use for translating the object. Normally, you'd want to declare the type of the object the array maps to as List or List or some such. This gives it the necessary type information... a JSON array can map to a List, and the String type parameter tells it what type to translate the array's contents to.

    The problem with the array in your example is that it isn't homogenous... it has a number and two strings in it. Generally, mixing types like this in an array/collection should be avoided. You can, however, declare the type of your array object as List... you'll just get the String form of the number.

提交回复
热议问题