gpt4 book ai didi

java - Json比较异常: Can't access getJSONArray in java

转载 作者:太空宇宙 更新时间:2023-11-04 10:59:13 24 4
gpt4 key购买 nike

 JSON1:
{
"array1": [
{
"id": "1",
"Name": "Xytrex Co.",
"Description": "Industrial Cleaning Supply Company",
"Account Number": "ABC15797531",
"Address": {
"Permanent": {
"Street": "st.road",
"pin": "789723"
},
"Temporary": {
"Street": "st.road",
"pin": "789723"
}
}
},

{
"id": "2",
"Name": "Xytrex Co.",
"Description": "Industrial Cleaning Supply Company",
"Account Number": "ABC15797531",
"Address": {
"Permanent": {
"Street": "st.road",
"pin": "789723"
},
"Temporary": {
"pin": "789723"
}
}
}
]
}

JSON2:

{
"array2": [
{
"id": "1",
"Name": "Xytrex Co.",
"Description": "Industrial Cleaning Supply Company",
"Account Number": "ABC15797531",
"Address": {
"Permanent": {
"Street": "st.road",
"pin": "789723"
},
"Temporary": {
"Street": "st.road",
"pin": "789723"
}
}
},

{
"id": "2",
"Name": "Xytrex Co.",
"Description": "Industrial Cleaning Supply Company",
"Account Number": "ABC15797531",
"Address": {
"Permanent": {
"Street": "st.road",
"pin": "789723"
},
"Temporary": {
"Street": "st.road",
"pin": "789723"
}
}
}
]
}

我使用的代码:

package com.company;

import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import org.skyscreamer.jsonassert.JSONAssert;
import org.skyscreamer.jsonassert.JSONCompareMode;
import com.google.gson.JsonParser;
import org.skyscreamer.jsonassert.JSONCompareMode;

import java.io.FileNotFoundException;
import java.io.FileReader;


public class Main {

public static void main(String[] args) throws FileNotFoundException {

Main cmp = new Main();
cmp.myTest();
}

public void myTest() throws FileNotFoundException {

JsonParser Parser = new JsonParser();
JsonObject obj1 = (JsonObject) Parser.parse(new
FileReader("/home/cloudera/Desktop/SampleJson/src/JSON1.json"));
JsonArray array1 = obj1.getAsJsonArray("array1");
JsonObject obj2 = (JsonObject)Parser.parse(new
FileReader("/home/cloudera/Desktop/SampleJson/src/JSON2.json"));
JsonArray array2 = obj1.getAsJsonArray("array2");
JSONAssert.assertEquals(array1, array2, JSONCompareMode.STRICT);
}
}

我期待的结果是那个键 Street JSON1 中缺失下"id":"2"或类似的东西可以提供正确的信息,帮助我们识别缺少的 key 来执行 Junit测试。

我在IDE中遇到的错误是

"java: cannot access org.json.JSONArray
class file for org.json.JSONArray not found".

请帮我解决这个问题。

最佳答案

我认为您对 JSONArray 对象类的初始化在这些行中似乎不正确。

jsonArray array1 = obj1.getAsJsonArray("array1");  // it may pron to the exception.
jsonArray array1 = obj1.getAsJsonArray("array1");

您尚未在方法 getAsJsonArray() 中传递正确的参数。您传递了硬编码值 "array1""array2",这不是转换为 JSONArray 的正确值。

看看here to help more

关于java - Json比较异常: Can't access getJSONArray in java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47091129/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com