简体   繁体   中英

parsing Json with gson nested

I'm having some trouble with GSON, mainly deserializing from JSON.

I have the following JSON:

{
    "1" : { 
        "name" : "NAME",
        "admins" : {
            "1": {
                "name2" : "NAME2",
                "admins2" : {
                    "1": { ... },
                    "2": { ... },
                    ......
                    "n": { ... }
                }
            },
            "2": { ... },
            "3": { ... },
            ......
            "n": { ... }
        } 
    },
    "2" : { ... },
    "3" : { ... },
    ......
    "n" : { ... }
 }

I need to find the Class to represent that json with gson, my problem is the "id" ( represented by the "n" correlatives integers nested)

I believe your best bet would be to use maps to allow for the dynamic keys. Something like:

public class JSWrapper {
public HashMap<String, JSMessage> messages;

public static class JSMessage {

    public String name;
    public Admins admins;
    }

    public static class Admins {
            ...
    }
}

It appears that your JSON has a recursive structure, though it isn't exactly clear from your example. If it is the case that your name and admins keys will be different, eventually being named namesn and adminsn, then you will need to represent even those as keys in a Map. I'm uncertain whether Gson can allow for that recursive structure, but I believe Maps will solve the dynamic key issue you are asking about.

Of course, once the data is in the maps, it is up to your code to understand what data (1, 2, .. n) is available within.

I am assuming you want a way to store keys which are Integers.
You want a way to use the Json String . Since they are integers, there can be "n" number of keys

1,2,3....n

and each key will have it values.

One way to do this is to use a HashMap.

The keys are stored in the Map as Integers.
Unlimited number of keys can be used.
Easily iterate through the key value pair.
Easily extendisible to add differernt objects.

/*Here we do the following steps
*  1. create the data
*  2. convert data to Json String using GSON
*  3. JSon String is used to populate the data bean using GSON.
*
*  Integers will be used as the key.
*/ 
public class CreateAccessGSON()
{
    public static void main(String[] args)
    {

         Gson gson = new Gson(); //instantiate gson here.

         //Creating the Data Object.
         HashMap<Integer,AdminBean> tmpAdminMap = new HashMap<Integer,AdminBean>();

         AdminBean adminOne1 = new AdminBean();
         adminOne1.setName("Joe");

         tmpAdminMap.put(1,adminOne1);   // key is an Integer 1

         AdminBean adminOne2 = new AdminBean();
         adminOne2.setName("Blow");

         tmpAdminMap.put(2,adminOne2);   // key is an Integer 2

         //Set the value of the Map.
         DataObjectBean dataObjectBean = new DataObjectBean();
         dataObjectBean.setAdminMap(tmpAdminMap);

         String jsonString = gson.toJson(dataObjectBean);

         System.out.println(jsonString ); // print the Json String.
          //Output will be as follows
         /*
           {
             "adminMap" : 
                    { 
                        "1" : {"name":"Joe"} ,
                        "2" : {"name":"Blow"}
                    }
           }
         */




         // Code to Convert Json String to the Associated object.
          DataObjectBean accessDataObjectBean = gson.fromJson(jsonString ,DataObjectBean);
          HashMap<Integer,AdminBean> retrieveAdminMap = accessDataObjectBean.getAdminMap();
          System.out.println(retrieveAdminMap.get(1).getName()); // Joe
          System.out.println(retrieveAdminMap.get(2).getName()); // Blow

          //get number of keys, we use the hashmap size.
          System.out.println("Num of keys : " + retrieveAdminMap.size()); // Num of keys : 2

          // You can use the Java Iterator to access each key and their values
          Set<Integer> setKey = retrieveAdminMap.keySet();
          for( Integer keys : setKey )
          {
                AdminBean eachAdmin = retrieveAdminMap.get(keys);
                System.out.println(eachAdmin.getName()); 
          }
    }
} 



//This class will store the Admin data. You can have more nested classes here.
// This class can further have more maps.
public class AdminBean
{
    private String name = "";

    public String getName()
    { 
        return name;
    }

    public String setName(String name)
    {
        this.name = name;
    }
}

// This main Java Bean which will be used to generate the JSON.
// Since we need as Integer as key, we use the HashMap to store it.
// HashMaps will allow storing unlimited Integers.
public class DataObjectBean{
    private HashMap<Integer,AdminBean> adminMap = new HashMap<Integer,AdminBean>();
    public String getAdminMap ()
    { 
        return adminMap ;
    }

    public String setAdminMap (String adminMap )
    {
        this.name = adminMap ;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM