【问题标题】:How to parse a JSON string using ggson to get field values如何使用 ggson 解析 JSON 字符串以获取字段值
【发布时间】:2016-11-08 14:21:07
【问题描述】:

我有一个示例 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在数组中,所以我需要遍历数组才能找到它。

你能告诉我我做错了什么吗?

【问题讨论】:

    标签: java json parsing


    【解决方案1】:

    可能的解决方案:

    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

    外部标识符:123456@mydomain.com

    【讨论】:

    • 谢谢。我也能够得到如下值
    【解决方案2】:
    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);
                    }
        }
    
    
         }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-31
      相关资源
      最近更新 更多