简体   繁体   中英

How to parse complex JSON string mix with JSON Arrays using GSON?

Below is my JSON String and I am trying to parse this JSON String using GSON as I am finding it pretty easy to work with.

{
"HasChanged":true,
"Version":1,
"LastModifiedDate":1390561121310,
    "DATACENTERS":
        [
            {
            "Name": "DC1",
            "TotalNumberOfServers":4,
            "PrimaryData":[{"0":"1", "1":"2", "2":"3", "3":"4"}],
            "SecondaryData":[{"0":"2", "1":"3", "2":"4", "3":"1"}],
            "MachineMapping":[{"3":"dc11115.dc1.domain.com"}, {"2":"dc11114.dc1.domain.com"}, {"1":"dc11113.dc1.domain.com"}, {"4":"dc11116.dc1.domain.com"}]
            },
            {
            "Name": "DC2",
            "TotalNumberOfServers":4,
            "PrimaryData":[{"1":"1", "5":"2", "2":"3", "6":"4"}],
            "SecondaryData":[{"7":"1", "0":"8", "2":"5", "10":"9"}],
            "MachineMapping":[{"3":"dc21147.dc2.domain.com"}, {"2":"dc21146.dc2.domain.com"}, {"1":"dc21145.dc2.domain.com"}, {"4":"dc21148.dc2.domain.com"}]
            }
        ]
}

After parsing the above JSON String, I need to store each DataCenter data in the below data structure -

Map<String, Map<String, String>> primaryData
Map<String, Map<String, String>> secondaryData
Map<String, Map<String, String>> machineMapping

For PrimaryData tag in the JSON String-

Here Key of `primaryData` map is `DC1` and value is {"0":"1", "1":"2", "2":"3", "3":"4"} which is for `PrimaryData` tag.
Similarly, another Key of `primaryData` map is `DC2` and value is {"1":"1", "5":"2", "2":"3", "6":"4"} which is for `PrimaryData` tag.

And also for SecondaryData tag in the JSON String-

Here Key of `secondaryData` map is `DC1` and value is {"0":"2", "1":"3", "2":"4", "3":"1"} which is for `SecondaryData` tag.
Similarly, another Key of `secondaryData` map is `DC2` and value is {"7":"1", "0":"8", "2":"5", "10":"9"} which is for `SecondaryData` tag.

And also for MachineMapping tag in the JSON String-

Here Key of `machineMapping` is `DC1` and value is {"3":"dc11115.dc1.domain.com"}, {"2":"dc11114.dc1.domain.com"}, {"1":"dc11113.dc1.domain.com"}, {"4":"dc11116.dc1.domain.com"} which is for MachineMapping tag.
Similarly another key of `machineMapping` is `DC2` and value is {"3":"dc21147.dc2.domain.com"}, {"2":"dc21146.dc2.domain.com"}, {"1":"dc21145.dc2.domain.com"}, {"4":"dc21148.dc2.domain.com"} which is for `MachineMapping` tag.

This is the first time I am working with parsing of this complex JSON String so I started working with GSON as I was finding it pretty easy to work with. This is what I have tried so far and I am able to extract most of the fields but not sure how to map PrimaryData object into a Map and then do the same thing for others?

private static Map<String, Map<String, String>> primaryData = new LinkedHashMap<String, Map<String, String>>();
private static Map<String, Map<String, String>> secondaryData = new LinkedHashMap<String, Map<String, String>>();
private static Map<String, Map<String, String>> machineMappedData = new LinkedHashMap<String, Map<String, String>>();

public static void main(String[] args) {

    String jsonLine = "my json string";

    JsonElement jelement = new JsonParser().parse(jsonLine);
    JsonObject jobject = jelement.getAsJsonObject();

    boolean changed = jobject.get("HasChanged").getAsBoolean();
    String timestamp = jobject.get("LastModifiedDate").getAsString();
    String version = jobject.get("Version").getAsString();

    System.out.println(changed);
    System.out.println(timestamp);
    System.out.println(version);

    if (changed) {
        JsonArray jarray = jobject.getAsJsonArray("DATACENTERS");
        for (int i = 0; i < jarray.size(); i++) {
            Map<String, String> data = new LinkedHashMap<String, String>();

            jobject = jarray.get(i).getAsJsonObject();
            String dcName = jobject.get("Name").getAsString();
            int servers = jobject.get("TotalNumberOfServers").getAsInt();
            System.out.println(dcName);
            System.out.println(servers);

            if (servers > 0) {
                JsonArray jarray1 = jobject.getAsJsonArray("PrimaryData");
                System.out.println(jarray1);
                for (int j = 0; j < jarray1.size(); j++) {
                    jobject = jarray1.get(j).getAsJsonObject();
                    System.out.println(jobject);

                    // not sure how to map the PrimaryData object to a Map here?

                }
            }
        }
    }
}

But I have got stuck on it and not sure how do I put the JSON object in a Map here? Can anyone help me with this?

What you should be doing is defining Java classes that your JSON maps to:

public class MyJsonResponse
{
    private boolean HasChanged;
    private int Version;
    private long LastModifiedDate;
    private List<DataCenter> DATACENTERS;

    // Getters/Setters for above
}

public class DataCenter
{
    private String Name;
    private int TotalNumberOfServers;
    private List<Map<String,String>> PrimaryData;
    private List<Map<String,String>> SecondaryData;
    private List<Map<String,String>> MachineMapping; 

    // getters and setters for all of the above
}

With those classes defined, it's as simple as:

MyJsonResponse response = new Gson().fromJson(jsonString, MyJsonResponse.class);

Also worth noting is that since the JSON variable names don't conform to the Java naming conventions, you should also convert them via the @SerializedName annotation.

@SerializedName("DATACENTERS")
private List<DataCenter> dataCenters;

as an example.

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