【问题标题】:Need simplest approach to to parsing this JSon content in Java需要最简单的方法来用 Java 解析这个 JSON 内容
【发布时间】:2017-07-23 01:44:09
【问题描述】:

我正在为 Web 服务编写 Java 客户端,需要将响应 JSON 对象解析为 Map<String,String>。

我无法控制 JSON 格式,并且客户端插入一个相对较旧的现有应用程序是一个内存猪,并且实际上有数百个其他 java 库依赖项。

所以我关心的是让我的客户端尽可能地摆脱外部依赖,并随着时间的推移减少内存占用,以避免大量内存使用和垃圾收集。

我知道我可以使用Gson 或Jackson 做到这一点,所以考虑到这些运行时限制,我正在寻找关于最佳方法的输入(我从未使用过 JSON。简单但我没有'没有快速阅读如何处理复杂类型)。

JSON 看起来像这样。我只需要关心 attribute 部分的名称/值对。其余的我可以忽略。

{
    "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": "****"
    }
}

感谢您的任何意见!

【问题讨论】:

  • 如果使用 json.org 会怎样? mvnrepository.com/artifact/org.json/json/20160810
  • 我会使用 JSONobject 并读取 JSON,然后使用 setter 创建一个 DAO 数据访问对象,以将信息存储到您的 Java 应用程序中,或者您甚至可以将其保留为 JSONobject。 docs.oracle.com/javaee/7/api/javax/json/JsonObject.html 你可以使用 getJsonObject("Key") 来返回值。
  • 您写了 我无法控制 JSON 格式所以收到的 json 可以有任何格式,而您作为示例提出的格式不是静态的格式?
  • 看看这个answer和这个answer,可能对你有帮助
  • 有几十个选项。您使用的是哪个 Java 版本/环境?您已经拥有哪些依赖项(Gson、Jackson、org.json、JSR-374 实现)?您想要简单的 JSON 树处理还是更复杂但更高效的流读取/分析以实现更高效的内存管理?

标签: java json jackson gson


【解决方案1】:

感谢您的有用回复。仅供参考,我与 Jackson 一起实现了一个通用解析器来在 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);
   }

【讨论】:

    猜你喜欢
    • 2012-07-28
    • 2016-03-06
    • 1970-01-01
    • 1970-01-01
    • 2011-08-22
    • 1970-01-01
    • 1970-01-01
    • 2011-05-09
    • 1970-01-01
    相关资源
    最近更新 更多