Using Gson to parse Json array and object with no name

前端 未结 4 1110
执念已碎
执念已碎 2021-02-15 23:02

I know there are many JSON with GSON questions but none of them relate to me directly. My JSON is formatted differently.

I have a JSON data I want to parse using GSON wh

4条回答
  •  别那么骄傲
    2021-02-15 23:40

    To check Json is valid use this tool http://jsonlint.com/

    Class Bar(
       private String _id;
       //create getter/setters
    {
    
    public class Item
    {
       String foo;
       List bar;
       List too;
    
       //Get set here
    }
    //this is also fine
    public class ItemList
    {
       List itemArray;
    
       //Get set here
    }
    

    you named of list of items "itemArray", but in your json you have not named the corresponding array of items "itemArray". So make it itemArray, The problem is not in your json, it is valid. Problem is in its representation for Gson, Gson map keys of json on the variables of object (i.e Java POJO) with same name. If the name of your list is Class is

    List itemArray;
    

    then the corresponding json array name should also be itemArray, take a look blow

    {
     itemArray: [
         {
          "foo":"1",
          "bar":[ { "_id":"bar1"} ],
          "too":["mall", "park"]
         }
      ]
    }
    

    so you can convert json into object like that

     Reader reader = new InputStreamReader(IOUtils.toInputStream(json_string));
     ItemList itemList = json.toObject(reader, ItemList.class);
    

    Take a look into blow reference for more details https://stackoverflow.com/questions/13625206/how-to-parse-the-result-in-java/13625567#13625567

提交回复
热议问题