如何使用ggson解析JSON字符串以获取字段值

时间:2016-11-08 14:21:08

标签: java json parsing

我有一个示例JSON,如下所示。我需要获取ASIdentiferExternalIdentifer等字段。我已将此JSON数据存储在字符串中。 使用GoogleJson作为模块(ggson)

JSON数据:

 {
        "DeviceCommon": {
            "ASIdentifier": "123",
            "DatadeliveyMechanism": "notify",
            "MobileOriginatorCallbackReference": {
                "url": "http://application.example.com/inbound/notifications/modatanotification/"
            },
            "AccessiblityCallbackReference": {
                "url": "http://application.example.com/inbound/notifications/accessibilitystatusnotification"
            }
        },
        "DeviceList": [{
            "ExternalIdentifer": "123456@mydomain.com",
            "msisdn": "123456",
            "senderName": "Device1",
            "MobileOriginatorCallbackReference": {
                "notifyURL": "http://application.example.com/inbound/notifications/modatanotification/"
            },
            "ConfigurationResultCallbackReference": {
                "notifyURL": "http://application.example.com/inbound/notifications/configurationResult"
            },
            "ASreferenceID": "AS000001",
            "NIDDduration": "1d"
        }]
    }

我创建了POJO类并使用下面的代码

解析数据
data = new Gson().fromJson(new FileReader("/home/raj/apache-tomcat-8.0.3/webapps/file.json"), Data.class);  
System.out.println(data);

输出:

Data{
  deviceCommon=DeviceCommon{
    asIdentifier='123'
    datadeliveyMechanism='notify'
    mobileOriginatorCallbackReference=http://application.example.com/inbound/notifications/modatanotification/
    accessiblityCallbackReference=http://application.example.com/inbound/notifications/accessibilitystatusnotification
  }
  deviceList=[DeviceListEntry{
    externalIdentifer='123456@mydomain.com'
    msisdn='123456'
    senderName='Device1'
    mobileOriginatorCallbackReference=http://application.example.com/inbound/notifications/modatanotification/
    configurationResultCallbackReference=http://application.example.com/inbound/notifications/configurationResult
    asReferenceID='AS000001'
    nidDduration='1d'
  }]
}

String jsonInString = gson.toJson(data);
System.out.println("String is"+ jsonInString);

输出:

String is{"DeviceCommon":{"ASIdentifier":"123","DatadeliveyMechanism":"notify","MobileOriginatorCallbackReference":{"url":"http://application.example.com/inbound/notifications/modatanotification/"},"AccessiblityCallbackReference":{"url":"http://application.example.com/inbound/notifications/accessibilitystatusnotification"}},"DeviceList":[{"ExternalIdentifer":"123456@mydomain.com","msisdn":"123456","senderName":"Device1","MobileOriginatorCallbackReference":{"notifyURL":"http://application.example.com/inbound/notifications/modatanotification/"},"ConfigurationResultCallbackReference":{"notifyURL":"http://application.example.com/inbound/notifications/configurationResult"},"ASreferenceID":"AS000001","NIDDduration":"1d"}]}

我需要解析此JSON字符串以获取ExternalIdentifierASIdentifier等单个字段。

我试过这样的事情,但是没有用。

JsonObject jobj = new Gson().fromJson(jsonInString, JsonObject.class);
String result = jobj.get("ASIdentifier").toString();
System.out.println("value is"+ result);

注意:ExternalIdentifier在数组中,所以我需要遍历数组才能找到它。

你能告诉我我做错了吗?

2 个答案:

答案 0 :(得分:0)

可能的解决方案:

String result = jobj.get("DeviceCommon").getAsJsonObject().get("ASIdentifier").getAsString();
System.out.println("ASIdentifier: "+ result);

JsonArray jsonArray = jobj.get("DeviceList").getAsJsonArray();
for (JsonElement device : jsonArray ) {
    result = device.getAsJsonObject().get("ExternalIdentifer").getAsString();
    System.out.println("ExternalIdentifer: "+ result);
}

输出:

ASIdentifier:123

ExternalIdentifer:123456@mydomain.com

答案 1 :(得分:0)

public static void printJson(JsonElement jsonElement,String key) {

            // Check whether jsonElement is JsonObject or not
            if (jsonElement.isJsonObject()) {
                Set<Entry<String, JsonElement>> ens = ((JsonObject) jsonElement).entrySet();
                if (ens != null) {
                    // Iterate JSON Elements with Key values
                    for (Entry<String, JsonElement> en : ens) {
                      //  System.out.println("##key is"+en.getKey() + " : ");
                        printJson(en.getValue(), en.getKey());
                       // System.out.println(en.getValue().getAsString());
                       // System.out.println(jsonElement.getAsString());
                    }
                }
            } 
         // Check whether jsonElement is Primitive or not
            else if (jsonElement.isJsonPrimitive()) {
                // print value as String
                System.out.println("###key is"+key);
                System.out.println("### value is"+jsonElement.getAsString());
            }  

            else if (jsonElement.isJsonArray()) {
                JsonArray jarr = jsonElement.getAsJsonArray();
                // Iterate JSON Array to JSON Elements
                System.out.println("\n###Array size is"+ jarr.size());
                for (JsonElement je : jarr) {
                    printJson(je,key);
                }
    }


     }