【问题标题】:Java - JSON Parsing to and FroJava - 来回解析 JSON
【发布时间】:2023-03-15 12:00:01
【问题描述】:

我一直在将多种方法与不同的 JSON 库结合起来,但似乎无法找到一种优雅的方法来在测试中与我的 JSON 文件进行相互转换。

JSON 文件如下所示:

[
  {
    "LonelyParentKey": "Account",
    "ProcessNames": [
      {"Name":  "ProcessOne",
      "Sequence": "1"
      },
      {
        "Name": "ProcessTwo",
        "Sequence": "2"
      },
      {
        "Name": "ProcessThree",
        "Sequence": "3"
      },
      {
        "Name": "ProcessFour",
        "Sequence": "4"
      }
    ]
  }
]

在使用 TestNG 的基于 QAF 的测试中,我尝试像这样导入“ProcessName”键的值:

  String lonelyParentKey = (String) data.get("LonelyParentKey");
  ArrayList processNames = (ArrayList) data.get("ProcessNames");

我已经看到在我使用的框架中,我有多个 JSON 库选项,在阅读其他 SO 帖子后一直在尝试使用 GSON。

那么,接下来在测试代码中:

  Gson gson = new Gson();
  JSONArray jsa = new JSONArray(processNames);

我试图在数据结构中创建一个包含 4 个子对象的对象,我可以在其中访问每个子对象的名称和序列键。

在查看我的jsa 对象时,它似乎具有我所追求的结构,但我如何访问第一个子对象的序列键?在 IntelliJ IDEA 的 REPL 中,执行 jsa.get(0) 会得到 "{"Name": "ProcessOne","Sequence": "1"}"

似乎地图可能有用,但需要帮助选择正确的数据结构和实施建议。

TIA!

【问题讨论】:

    标签: java json multidimensional-array


    【解决方案1】:

    不确定您使用的是哪个库,但它们都提供几乎相同的方法。 JSONArray 看起来像 org.json.JSONArray,所以应该是

    JSONArray jsa = new JSONArray(processNames);
    int sequenceFirstEntry = jsa.getJSONObject(0).getInt("Sequence");
    

    一些 JsonArray 实现也实现了 Iterable,那么这也可以工作

    JSONArray jsa = new JSONArray(processNames);
    for (JSONObject entry : jsa) {
        int sequenceFirstEntry = entry.getInt("Sequence");    
    }
    

    【讨论】:

    • 感谢您的发帖。最终使用jsa.getJSONObject(indexNumHere).get("KeyNameIWant") 并满足我的需求。真的很感激!
    【解决方案2】:

    有什么理由不为您的模型使用 DTO 类?

    例如

    class Outer {
        String lonelyParentKey;
        List<Inner> processNames;
    
        // getter/setter
    }
    

    class Inner {
        String name;
        String sequence;
    
        // getter/setter
    }
    

    现在您的库应该能够将您的 JSON 字符串反序列化为列表。我一直在使用 Jackson 而不是 GSON,但在 GSON 中应该是类似的:

    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.configure(ACCEPT_CASE_INSENSITIVE_PROPERTIES, true);
    List<X> x = objectMapper.readValue(json, new TypeReference<List<X>>() {});
    

    【讨论】:

    • 因为我正在编写可能很快会发展的测试,所以现在想远离任何自定义类型,但看起来是一种普遍的好方法。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2017-02-20
    • 1970-01-01
    • 1970-01-01
    • 2011-08-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多