开发者

Gson exception while reading Json with JsonArray and JsonObject

开发者 https://www.devze.com 2023-04-03 17:47 出处:网络
I am trying to call a json response using Gson. But it contains a JSONArray object on one place and a JSONObject in place in the same hierarchy, here my json response is:

I am trying to call a json response using Gson. But it contains a JSONArray object on one place and a JSONObject in place in the same hierarchy, here my json response is:

"{"SERVICES":{"Results":[{"Items":{"Item":[{"@Id":"10"},{"@Id":"12"}]}}, 
  {"Items":{"Item":{"@Id":"13"}}}]}}"

in the structure it is in this hierarchy,

    {"SERVICES":
        {"Results":
            [
             {"Items":
                {"Item":
                    [
                     {"@Id":"10"},
                     {"@Id":"12"}
                    ]
                }
             },
             {"Items":
                {"Item":
                    {"@Id":"13"}
                }
             }
             ]
        }
    }

Here first 'Item' element contain an array and second one is an object. Below is my code,

import java.util.Iterator;
import java.util.List;
import com.google.gson.Gson;
import com.google.gson.annotations.SerializedName;

public class Next { 
public static void main(String args[]){

    String jsonData = Services.getJsonData();   //{"SERVICES":{"Results":[{"Items":{"Item":[{"@Id":"10"},{"@Id":"12"}]}}, {"Items":{"Item":{"@Id":"13"}}}]}}    

    TRes开发者_StackOverflow中文版ponseInfo responseInfo = new Gson().fromJson(jsonData, TResponseInfo.class);        
    }

class TResponseInfo{
    TServicesInfo SERVICES;
}

class TServicesInfo {
    List<TResultsInfo> Results;
}

class TResultsInfo {
    TItemsInfo Items;
}

class TItemsInfo {
    List<TItemInfo> Item;
    //TItemInfo Item;
}

class TItemInfo {
    @SerializedName("@Id")
    int Id;
}

Here I am getting the exception:

failed to deserialize json object {"@Id":"13"} given the type java.util.List

and message: This is not a JSON Array.


Update: Your Json seem to be wrong, your Item: is an array, but the seconds field in your JSON is an object.

First you have:

"Item":
                [
                 {"@Id":"10"},
                 {"@Id":"12"}
                ]

then you have:

"Item":
                {"@Id":"13"}

This should be:

 "Item":
               [
                {"@Id":"13"}
               ]

It can be hard to manage generics with Gson. I would suggest you to use arrays instead. E.g. something like this:

class TResponseInfo{
    TServicesInfo SERVICES;
}

class TServicesInfo {
    TResultsInfo[] Results; // an array  instead of a generic List
}

class TResultsInfo {
    TItemsInfo Items;
}

class TItemsInfo {
    TItemInfo[] Item; // an array instead of a generic List
}
0

精彩评论

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