解析简单的JSON Inputstream时,我收到com.google.gson.JsonSyntaxException
我的json就是这个。
{ “logdata”:[{ “millis”:“1000”, “光”:“333” }, { “millis”:“2000”, “光”:“333” } ] }
Java类 -
import java.util.List;
public class Datalist {
private List<NavData> logdata;
/**
* @return the logdata
*/
public List<NavData> getLogdata() {
return logdata;
}
/**
* @param logdata the logdata to set
*/
public void setLogdata(List<NavData> logdata) {
this.logdata = logdata;
}
public class NavData {
private String millis;
private String light;
/**
* @return the millis
*/
public String getMillis() {
return millis;
}
/**
* @param millis the millis to set
*/
public void setMillis(String millis) {
this.millis = millis;
}
/**
* @return the light
*/
public String getLight() {
return light;
}
/**
* @param light the light to set
*/
public void setLight(String light) {
this.light = light;
}
}
Json输入流读取器类 - 而assetData是上面json的inputStream。
JsonReader reader = new JsonReader(new InputStreamReader(assetData, "UTF-8"));
Gson gson = new GsonBuilder().create();
Datalist out = gson.fromJson(reader, Datalist.class);
System.out.println(".."+out.getLogdata());
答案 0 :(得分:1)
问题是因为您无法将字符串列表转换为包含以下项目的列表:
{
"millis": "1000",
"light": "333",
"temp": "78.32",
"vcc": "3.54"
}
如果要转换为这些项目的列表,则需要创建包含这些项目的类,该属性将为:
@Expose
private List<NavData> logdata;
NavData 是具有这些参数的类
import com.google.gson.annotations.Expose;
public class NavData {
@Expose
private String millis;
@Expose
private String light;
public String getMillis() {
return millis;
}
public void setMillis(String millis) {
this.millis = millis;
}
public String getLight() {
return light;
}
public void setLight(String light) {
this.light = light;
}
}
阅读inputStream:
StringBuilder stringBuilder = new StringBuilder();
CharBuffer charBuffer = CharBuffer.allocate(1024);
while (yourInputStream.read(charBuffer) > 0) {
charBuffer.flip();
stringBuilder.append(charBuffer.toString());
charBuffer.clear();
}
最后:
Gson gson = new GsonBuilder().enableComplexMapKeySerialization()
.excludeFieldsWithoutExposeAnnotation().serializeNulls().create();
Datalist result = gson.fromJson(stringBuilder.toString(), Datalist.class);