org.json.JSONException 在尝试解析复杂的 JSON 子部分时发生

huangapple go评论88阅读模式
英文:

org.json.JSONException when trying to parse complex JSON subsection

问题

// 获取为jsonString后
JSONObject productsJsonObject = (JSONObject) new JSONTokener(jsonString).nextValue();

// 这将记录上面列出的正确的JSON
logger.info("productsJsonObject = {}", productsJsonObject); 

// 异常发生在这里:
JSONObject productTypeJsonSection = (JSONObject) productsJsonObject.get("productTypes");

抛出以下异常:

org.json.JSONException: 未找到 JSONObject["productTypes"].
        at org.json.JSONObject.get(JSONObject.java:422) ~[json-NOT_KNOWN.jar:?]
英文:

Am facing impediments when using Java 1.8 and the org.json lib to marshal & parse a complex JSON object...

JSON dependency:

<dependency>
    <groupId>org.json</groupId>
    <artifactId>json</artifactId>
    <version>NOT_KNOWN</version>
</dependency>

JSON response payload:

{
	"products": {
		"productTypes": {
			"storeId": "abc123"
			"names": [
				"sku": "123",
				"prices": {
					"salesTax": .2,
					"wholeSalePrice": 5,
					"retailPrice": 10
				}
			]

		}
	}
}

// After obtaining as a jsonString
JSONObject productsJsonObject = (JSONObject) new JSONTokener(jsonString).nextValue();

// This logs the correct the JSON listed above
logger.info("productsJsonObject = {}", productsJsonObject); 

// Exception happens here:
JSONObject productTypeJsonSection = (JSONObject) productsJsonObject.get("productTypes");

This exception is thrown:

org.json.JSONException: JSONObject["productTypes"] not found.
        at org.json.JSONObject.get(JSONObject.java:422) ~[json-NOT_KNOWN.jar:?]

答案1

得分: 2

首先,当我在你问题中提供的JSON字符串上运行你的代码时,我得到了一个错误:

Exception in thread "main" org.json.JSONException: Expected a ',' or ']' at 128 [character 26 line 6]

正如@TimMoore在他的评论中所写的:

名为 productsJsonObject 的对象实际上是包含产品对象的顶级对象。

你有一个没有命名的JSON对象,其中包含一个名为 products 的成员。因此,在你执行以下操作后:

JSONObject productsJsonObject = (JSONObject) new JSONTokener(jsonString).nextValue();

你需要执行以下操作:

productsJsonObject = (JSONObject) productsJsonObject.get("products");

然后,你可以执行以下操作:

JSONObject productTypesJsonObject = (JSONObject) productsJsonObject.get("productTypes");

以下是一个完整的示例,包括我对JSON字符串所做的更改,以克服上面提到的异常。

请注意,该代码使用了JDK 15中首次添加的文本块

import org.json.JSONObject;
import org.json.JSONTokener;

public class OrgJsonT {

    public static void main(String[] args) {
        String json = """
{
    "products": {
        "productTypes": {
            "storeId": "abc123",
            "names": [
                {
                    "sku": 123
                },
                {
                    "prices": {
                        "salesTax": .2,
                        "wholeSalePrice": 5,
                        "retailPrice": 10
                    }
                }
            ]
        }
    }
}
""";
        JSONTokener jsonTokener = new JSONTokener(json);
        JSONObject jsonObject = (JSONObject) jsonTokener.nextValue();
        JSONObject productsJsonObject = (JSONObject) jsonObject.get("products");
        JSONObject productTypesJsonObject = (JSONObject) productsJsonObject.get("productTypes");
        System.out.println(productTypesJsonObject);
    }
}

运行上述代码会打印以下内容:

{"names":[{"sku":123},{"prices":{"wholeSalePrice":5,"salesTax":".2","retailPrice":10}}],"storeId":"abc123"}
英文:

First of all, when I ran your code on the JSON string in your question, I got an error:

Exception in thread "main" org.json.JSONException: Expected a ',' or ']' at 128 [character 26 line 6]

As @TimMoore wrote in his comment:
> The object named productsJsonObject is actually the top level object that contains the products object.

You have an unnamed JSON object that contains a single member named products. Hence after you do this:

JSONObject productsJsonObject = (JSONObject) new JSONTokener(jsonString).nextValue();

you need to do this:

productsJsonObject = (JSONObject) productsJsonObject.get("products");

Then you can do this:

JSONObject productTypesJsonObject = (JSONObject) productsJsonObject.get("productTypes");

Here is a complete example – including changes I made to the JSON string in order to overcome the exception, above.

Note that the code uses text blocks which were first added in JDK 15.

import org.json.JSONObject;
import org.json.JSONTokener;

public class OrgJsonT {

    public static void main(String[] args) {
        String json = """
{
    "products": {
        "productTypes": {
            "storeId": "abc123",
            "names": [
                {
                    "sku": 123
                },
                {
                    "prices": {
                        "salesTax": .2,
                        "wholeSalePrice": 5,
                        "retailPrice": 10
                    }
                }
            ]
        }
    }
}
                """;
        JSONTokener jsonTokener = new JSONTokener(json);
        JSONObject jsonObject = (JSONObject) jsonTokener.nextValue();
        JSONObject productsJsonObject = (JSONObject) jsonObject.get("products");
        JSONObject productTypesJsonObject = (JSONObject) productsJsonObject.get("productTypes");
        System.out.println(productTypesJsonObject);
    }
}

Running the above code prints the following:

{"names":[{"sku":123},{"prices":{"wholeSalePrice":5,"salesTax":".2","retailPrice":10}}],"storeId":"abc123"}

huangapple
  • 本文由 发表于 2023年7月10日 18:00:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/76652657.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定