使用带有嵌套对象的 Gson 2.2.4 和 JsonReader 进行流式传输。
JSON:
{
"name": "David",
"address": {
"city": "Bangalore"
},
"role": "Manager"
}
POJO 类:
public class Data {
private String name;
private String role;
private Address address;
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
@Override
public String toString(){
return getName() + "::"+getRole()+"::"+getAddress().getCity();
}
}
public class Address {
private String city;
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
}
我的代码:
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonToken;
public class TestReader {
public static void main(String[] args) throws IOException {
InputStream is = new FileInputStream("test.txt");
InputStreamReader isr = new InputStreamReader(is);
JsonReader reader = new JsonReader(isr);
Data data = new Data();
data.setAddress(new Address());
String key = null;
while (reader.hasNext()) {
JsonToken token = reader.peek();
switch (token) {
case BEGIN_OBJECT:
reader.beginObject();
break;
case END_OBJECT:
reader.endObject();
break;
case BEGIN_ARRAY:
reader.beginArray();
break;
case END_ARRAY:
reader.endArray();
break;
case NAME:
key = reader.nextName();
break;
case STRING:
if ("name".equals(key))
data.setName(reader.nextString());
else if ("role".equals(key))
data.setRole(reader.nextString());
else if ("city".equals(key))
data.getAddress().setCity(reader.nextString());
break;
case NULL:
reader.nextNull();
break;
case END_DOCUMENT:
break;
default:
break;
}
}
reader.close();
System.out.println(data);
}
}
它打印“David::null::Bangalore”,并且在嵌套对象之后无法解析任何内容。如果我将 JSON 更改为
{
"name": "David",
"role": "Manager",
"address": {
"city": "Bangalore"
}
}
它工作正常并打印“David::Manager::Bangalore”。尝试了很多,但不确定我错过了什么。