我存储在字符串中的json的结构是:
{
"0": {
"PDate": "2019-02-25 00:00:00.0000000",
"DDate": "2019-06-25 00:00:00.0000000",
"Document": "FC",
"Direction": "CALLE ...."
},
"1": {
"PDate": "2019-02-25 00:00:00.0000000",
"DDate": "2019-06-25 00:00:00.0000000",
"Document": "FC",
"Direction": "CALLE ...."
}
}
我正在使用以下代码,但在最后一行显示错误:
if (response.isSuccessful()){
Object object = response.body();
String jsonString = String.valueOf(object);
Gson gson = new Gson();
Type empMapType = new TypeToken<Map<Integer, Object>>() {}.getType();
Map<Integer, Object> nameObjectJson = gson.fromJson(jsonString, empMapType);
}
错误消息:
com.google.gson.JsonSyntaxException: com.google.gson.stream.MalformedJsonException: Unterminated object at line 1 column 29 path $..PostingDate
请,我需要帮助。谢谢
答案 0 :(得分:0)
首先-创建POJO / Model类以转换您的响应。
public class SomeModel{
@SerializedName("name")
@Expose
private String name = null;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
声明您的回复
Gson gson = new Gson();
SomeModelResponse response = gson.toJson(result, SomeModel.class);
如果您将多次使用Gson对象-最好创建一个单例对象,因为每次创建它的新实例时-都会占用大量内存。
添加检查后:
if(response !=null && response.getName() !=null){
if(response.getName().equalIgnoreCase("some name")){
// show toast Result Success !!! and move to next screen
}
else if(response.getName().equalIgnoreCase("another name")){
// Invalid Response !!! your logic here
}
}
也不要忘记检查您期望得到什么样的答复。它不应该是Object.class
答案 1 :(得分:0)
我注意到错误消息包括“ $ .. PostingDate” 但我无法澄清“ response.body()”的内容,请尝试以下方法:
String jsonString = String.valueOf(object);
=>
String jsonString = object.toString();
并尝试打印出来看看它是什么。
答案 2 :(得分:0)
class Example {
@SerializedName("PDate")
@Expose
private String pDate;
@SerializedName("DDate")
@Expose
private String dDate;
@SerializedName("Document")
@Expose
private String document;
@SerializedName("Direction")
@Expose
private String direction;
public String getPDate() {
return pDate;
}
public void setPDate(String pDate) {
this.pDate = pDate;
}
public String getDDate() {
return dDate;
}
public void setDDate(String dDate) {
this.dDate = dDate;
}
public String getDocument() {
return document;
}
public void setDocument(String document) {
this.document = document;
}
public String getDirection() {
return direction;
}
public void setDirection(String direction) {
this.direction = direction;
}
}
现在解析它
Gson gson = new Gson();
String json = "{\n" +
"\"0\": {\n" +
" \"PDate\": \"2019-02-25 00:00:00.0000000\",\n" +
" \"DDate\": \"2019-06-25 00:00:00.0000000\",\n" +
" \"Document\": \"FC\",\n" +
" \"Direction\": \"CALLE ....\" \n" +
" },\n" +
"\"1\": {\n" +
" \"PDate\": \"2019-02-25 00:00:00.0000000\",\n" +
" \"DDate\": \"2019-06-25 00:00:00.0000000\",\n" +
" \"Document\": \"FC\",\n" +
" \"Direction\": \"CALLE ....\" \n" +
" }\n" +
"}";
Type type = new TypeToken<Map<String, Example>>(){}.getType();
Map<String, Example> myMap = gson.fromJson(json, type);
//Log.d("===", myMap.get("0").document);