How can I deserialize an array inside a JSON object?

前端 未结 2 1002
遥遥无期
遥遥无期 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:47

    your "array" is an Array. so in watchList class

        public class Watchlist {
        private int itemn0;
        private int itemn1;
        private int itemn2;
        private List<watchListarray> array;
    
     //constructor
      //getter & setter of all
    
    }
    
    now watchListarray class
     public class watchListarray{
      String arrayItem1="";
      String arrayItem2="";
      String arrayItem3="";
    //constructor 
     //getter & setters of all
    }
    

    Now use download Gson refer: http://primalpop.wordpress.com/2010/06/05/parsing-json-using-gson-in-android/

    0 讨论(0)
  • 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<String> or List<Integer> 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<String>... you'll just get the String form of the number.

    0 讨论(0)
提交回复
热议问题