[英]From Json to Object, Java
我有一個 json 對象數組,看起來像這樣(但有 30k 行):
{
"Foglio1": [
{
"istat": "1001",
"cap": "10011"
},
{
"istat": "1002",
"cap": "10060"
},
{
"istat": "1003",
"cap": "10070"
},
{
"istat": "1004",
"cap": "10010"
},
{
"istat": "1006",
"cap": "10040"
}
]
}
我的課程:
public class Test {
public static void main(String[] args) throws IOException {
BufferedReader reader=new BufferedReader(new FileReader("italy_cap.json"));
String cap=reader.readLine();
Gson g = new Gson();
Foglio1 p=null;
while(cap!=null) {
p = g.fromJson(cap, Foglio1.class);
cap=reader.readLine();
}
System.out.println(p);
}
}
public class Foglio1 {
ArrayList <Cap> Foglio1;
}
public class Cap {
String istat;
String cap;
public String getIstat() {
return istat;
}
public void setIstat(String istat) {
this.istat = istat;
}
public String getCap() {
return cap;
}
public void setCap(String cap) {
this.cap = cap;
}
}
我想閱讀 json 並將其轉換為 java object 以進行解析,但我不知道如何使其工作。 它給我的錯誤是:
Exception in thread "main" com.google.gson.JsonSyntaxException: java.io.EOFException: End of input at line 1 column 14 path $.Foglio1[0]
at com.google.gson.Gson.fromJson(Gson.java:937)
at com.google.gson.Gson.fromJson(Gson.java:892)
at com.google.gson.Gson.fromJson(Gson.java:841)
at com.google.gson.Gson.fromJson(Gson.java:813)
at net.codejava.ws.Test.main(Test.java:21)
Caused by: java.io.EOFException: End of input at line 1 column 14 path $.Foglio1[0]
at com.google.gson.stream.JsonReader.nextNonWhitespace(JsonReader.java:1401)
at com.google.gson.stream.JsonReader.doPeek(JsonReader.java:549)
at com.google.gson.stream.JsonReader.hasNext(JsonReader.java:414)
at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.read(CollectionTypeAdapterFactory.java:81)
at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.read(CollectionTypeAdapterFactory.java:61)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.read(ReflectiveTypeAdapterFactory.java:131)
at `enter code here`com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:222)
at com.google.gson.Gson.fromJson(Gson.java:927)
作為替代方案,你能給我關於大 json 庫的任何想法嗎?
感謝您的幫助:)
JSON 不是面向行的數據格式,嘗試逐行讀取它是行不通的。 您可以一次將整個文件提供給 Gson:
static void main(String[] args) throws IOException {
try (BufferedReader reader=new BufferedReader(new FileReader("italy_cap.json"))) {
Gson g = new Gson();
Foglio1 p = g.fromJson(reader, Foglio1.class);
System.out.println(p);
}
}
If your JSON is so big that the objects you create from it don't fit in memory, you can switch to reading it as a stream , but that may require extensive changes to the rest of your program. 例如,您可能必須將Foglio1
class 中的列表更改為其他內容,或者完全刪除Foglio1
class。 在不知道你程序的rest的情況下,是不可能說出來的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.