gpt4 book ai didi

java - Json 数据无法正确从 URL 读取

转载 作者:行者123 更新时间:2023-11-30 06:32:11 25 4
gpt4 key购买 nike

我正在尝试从 url 读取 Json 数据。以下 json 格式无法从链接中正确读取为 jsonObject。我已经实现了代码,但仍然出现错误。需要有关该错误的一些帮助。请注意,我没有创建任何模型类来解析 json 数据,而是直接从 URL 调用,然后在控制台中打印该 json 数据。

Json 数据:

[
{
"countryId": "BE",
"vat": 0.21,
"maxShortestEdge": 60,
"maxMiddleEdge": 80,
"maxLongestEdge": 200,
"maxLengthGirth": 300,
"maxWeight": 40,
"languages": [
"fr",
"nl",
"en"
],
"defaultLanguage": "nl",
"currency": {
"id": "EUR",
"messageId": "general.units.currency.eur"
}
},
{
"countryId": "DE",
"vat": 0.19,
"maxShortestEdge": 60,
"maxMiddleEdge": 80,
"maxLongestEdge": 200,
"maxLengthGirth": 300,
"maxWeight": 40,
"languages": [
"de",
"en"
],
"defaultLanguage": "de",
"currency": {
"id": "EUR",
"messageId": "general.units.currency.eur"
},
"tracking": {
"google": "UA-64686897-5",
"facebook": "591925420983129"
}
},
{
"countryId": "LU",
"vat": 0.17,
"maxShortestEdge": 60,
"maxMiddleEdge": 80,
"maxLongestEdge": 200,
"maxLengthGirth": 300,
"maxWeight": 40,
"languages": [
"fr",
"en"
],
"defaultLanguage": "fr",
"currency": {
"id": "EUR",
"messageId": "general.units.currency.eur"
}
}
]

实现的代码:

public class RestTest {

public static void main(String[] args) {
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("proxy.xxxxx.com",8080));

try {

URL url = new URL("http://test.one.de/api/");
HttpURLConnection http = (HttpURLConnection)url.openConnection(proxy);
InputStream ins = http.getInputStream();
JsonParser jsonParser = new JsonParser();
JsonObject jsonObject = (JsonObject)jsonParser.parse(new InputStreamReader(ins));
System.out.println(jsonObject);
}
catch (MalformedURLException e)
{
e.printStackTrace();
} catch (IOException e) {

e.printStackTrace();
}

}

}

获取错误:

Exception in thread "main" com.google.gson.JsonSyntaxException: com.google.gson.stream.MalformedJsonException: Use JsonReader.setLenient(true) to accept malformed JSON at line 1 column 12 path $
at com.google.gson.JsonParser.parse(JsonParser.java:65)
at com.test.api.RestTest.main(RestTest.java:113)
Caused by: com.google.gson.stream.MalformedJsonException: Use JsonReader.setLenient(true) to accept malformed JSON at line 1 column 12 path $
at com.google.gson.stream.JsonReader.syntaxError(JsonReader.java:1567)
at com.google.gson.stream.JsonReader.checkLenient(JsonReader.java:1416)
at com.google.gson.stream.JsonReader.doPeek(JsonReader.java:546)
at com.google.gson.stream.JsonReader.peek(JsonReader.java:429)
at com.google.gson.JsonParser.parse(JsonParser.java:60)
... 1 more

最佳答案

尝试使用JsonArray而不是JsonObject。您可以尝试读取字符串然后进行转换

String json = IOUtils.toString(ins, encoding);
JsonArray jsonArray = new JsonArray(json);

关于java - Json 数据无法正确从 URL 读取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45878773/

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