2017-03-03 26 views
2

我在写一个Java客户端到一个Web服务,并且需要将响应JSON对象解析为一个Map<String,String>需要最简单的方法来解析Java中的这个JSon内容

我没有对JSON格式的控制,而客户端插入相对较旧的现有应用程序是一个内存管理器,并且具有数百个其他java库依赖项。

所以我的担心是让我的客户端尽可能地没有外部依赖,并且随着时间的推移最小的内存占用量可以避免大量内存使用和垃圾回收。

我知道我可以Gson所以Jackson正在寻找输入来考虑这些运行时的限制,最好的方法(我从来没有使用JSON。简单的,我并没有在快速细读看到如何做到这一点处理复杂类型)。

JSON看起来像这样。我只需要关注属性部分名称/值对。剩下的我可以忽略。

{ 
    "responseInfo": { 
     "responseMsg": "Success", 
     "timeStamp": "***", 
     "transactionId": "***" 
    }, 
    "callerId": "****", 
    "locale": "en-US", 
    "userId": "***", 
    "attributes":[ 
    { 
     "attributeName": "AN", 
     "attributeDescription": "Account Number", 
     "attributeValue": "*****" 
    }, 
    { 
     "attributeName": "EA", 
     "attributeDescription": "Email Address", 
     "attributeValue": "****@****" 
    }, 
    { 
     "attributeName": "SOI", 
     "attributeDescription": "someotherinfo", 
     "attributeValue": "****" 
    } 
} 

感谢您的任何意见!

+0

如果您使用json.org? https://mvnrepository.com/artifact/org.json/json/20160810 – alayor

+0

我会使用JSONobject并在JSON中读取,然后用setter创建一个DAO数据访问对象以将信息存储到Java应用程序中,或者您甚至可以离开它作为一个JSON对象。 http://docs.oracle.com/javaee/7/api/javax/json/JsonObject.html你可以使用getJsonObject(“Key”),它会返回值。 – JesseBoyd

+0

您写过**我无法控制JSON格式**因此,收到的json可以具有任何格式,并且您放置的问题例如不是静态格式? –

回答

0

感谢您的有益回应。仅供参考,我与杰克逊一起去了,并实现了一个通用解析器来查找JSon块中的名称/值对。我对所需的灵活性和少量代码感到满意。作为参考,这是我写的代码:

final ObjectMapper mapper = new ObjectMapper(); 
    final ArrayType type = mapper.getTypeFactory().constructArrayType(Map.class); 

    try { 
     if (attrBlockName == null || attrBlockName.length() == 0) 
      return mapper.readValue(f, type); 
     JsonNode base = new ObjectMapper().readTree(f); 
     if (base == null) 
      return JSonHttpClientAttributeProvider.PROVIDER_FAILED_UNKNOWN; 
     JsonNode attrJson = base.get(attrBlockName); 
     if (attrJson == null) 
      return JSonHttpClientAttributeProvider.PROVIDER_FAILED_UNKNOWN; 
     Map<String, String>[] mapArray = mapper.readValue(mapper.treeAsTokens(attrJson), type); 
     for (Map<String, String> newmap : mapArray) { 
      if (newmap.containsKey(attrNameField) && newmap.containsKey(attrValueField)) 
       map.put(newmap.get(attrNameField), newmap.get(attrValueField)); 
     } 
     return PROVIDER_SUCCEEDED; 
    } catch (IOException ioe) { 
     throw new MyExceptionClass("Exception occurred during request", ioe); 
    } 
相关问题