我想從url讀取Json數據。在下面的json格式中,不能正確地從鏈接讀取jsonObject。我有代碼實現,但仍然出現錯誤。需要一些關於錯誤的幫助。請注意,我沒有創建任何模型類來解析json數據,而是直接從URL調用,然後在控制檯中打印該json數據。Json數據沒有正確地從URL讀取
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
此鏈接應該是對您有用https://stackoverflow.com/questions/2591098/how-to-parse-json-in-java – Vignajeth