我有一个 json 文件,其中包含许多如下元素:
{
"code" : "hfuiew89",
"type" : "location",
"coordinates" : [ { "lat" : 40.9861, "lon" : 29.1046, "index" : 1 },
{ "lat" : 40.9976, "lon" : 29.1153, "index" : 2 },
{ "lat" : 40.9809, "lon" : 29.2194, "index" : 3 }]
}
{
"code" : "klsdsjh",
"type" : "location",
"relatedTags" : [ "kolmha" ],
"coordinates" : [ { "lat" : 40.9808, "lon" : 29.1605, "index" : 1 },
{ "lat" : 40.9965, "lon" : 29.1672, "index" : 2 }]
}
我想用 gson 读取该文件,但我找到的所有示例仅适用于一个元素。因此,在读取第一个之后,抛出“预期 EOF”异常。我怎样才能克服这个问题?
物有所值...
下面的说法是不正确的。 Gson 没有内置功能来简单地处理此类 JSON 序列的反序列化。 (看评论。)
如果可以选择在 JSON 与 Java API 之间进行切换,Jackson确实有这样的功能,如下所示。
输入.json
{
"name":"A"
}
{
"name":"B"
}
JacksonFoo.java
import static com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility.ANY;
import static com.fasterxml.jackson.annotation.PropertyAccessor.FIELD;
import java.io.File;
import java.util.Iterator;
import com.fasterxml.jackson.databind.ObjectMapper;
public class JacksonFoo
{
public static void main(String[] args) throws Exception
{
ObjectMapper mapper = new ObjectMapper().setVisibility(FIELD, ANY);
Iterator<Thing> thingsIterator = mapper.reader(Thing.class).readValues(new File("input.json"));
while (thingsIterator.hasNext())
{
System.out.println(thingsIterator.next());
}
}
}
class Thing
{
private String name;
@Override
public String toString()
{
return String.format("Thing: name=%s", name);
}
}
Output:
Thing: name=A
Thing: name=B
Update:使用 Gson 的类似解决方案。
GsonFoo.java
import java.io.FileReader;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonStreamParser;
public class GsonFoo
{
public static void main(String[] args) throws Exception
{
Gson gson = new GsonBuilder().create();
JsonStreamParser parser = new JsonStreamParser(new FileReader("input.json"));
while(parser.hasNext())
{
System.out.println(gson.fromJson(parser.next(), Thing.class));
}
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)