我正在尝试将json字符串转换为bean对象,如下所示 -
PinsRequestTo objPinsRequestTo = new PinsRequestTo();
objPinsRequestTo = new Gson().fromJson(pinMessageJson, PinsRequestTo.class);
My Bean对象如下
public class PinsRequestTo {
private String message;
private JsonArray keypattern_id_list;
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public JsonArray getKeypattern_id_list() {
return keypattern_id_list;
}
public void setKeypattern_id_list(JsonArray keypattern_id_list) {
this.keypattern_id_list = keypattern_id_list;
}
}
json字符串如下
{
"keypattern_id_list":["C0000011MSZPIN2015010760417236","C0000011MSZPIN2015010760294357"]
}
我在此过程中遇到异常,如下所示
com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 2 column 25
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:176)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.read(ReflectiveTypeAdapterFactory.java:93)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:172)
at com.google.gson.Gson.fromJson(Gson.java:795)
at com.google.gson.Gson.fromJson(Gson.java:761)
at com.google.gson.Gson.fromJson(Gson.java:710)
at com.google.gson.Gson.fromJson(Gson.java:682)
......
......
我想用Json字符串中的数组设置PinsRequestTo的属性keypattern_id_list。我该怎么办。如果还有其他方法,请告诉我。
提前致谢
答案 0 :(得分:0)
在 PinsRequestTo 类中将keypattern_id_list
变量类型从JsonArray
更改为List<String>
,然后它应如下所示:
public class PinsRequestTo {
private String message;
private List<String> keypattern_id_list;
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public List<String> getKeypattern_id_list() {
return keypattern_id_list;
}
public void setKeypattern_id_list(List<String> keypattern_id_list) {
this.keypattern_id_list = keypattern_id_list;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("PinsRequestTo [message=").append(message)
.append(", keypattern_id_list=").append(keypattern_id_list)
.append("]");
return builder.toString();
}
}
和反序列化逻辑如下:
String pinMessageJson = "{\"keypattern_id_list\":[\"C0000011MSZPIN2015010760417236\",\"C0000011MSZPIN2015010760294357\"]}";
PinsRequestTo objPinsRequestTo = new Gson().fromJson(pinMessageJson, PinsRequestTo.class);
System.out.println(objPinsRequestTo);
这是print语句的输出:
PinsRequestTo [message=null, keypattern_id_list=[C0000011MSZPIN2015010760417236, C0000011MSZPIN2015010760294357]]
gson的maven依赖是:
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.2.2</version>
</dependency>