gpt4 book ai didi

Android - Retrofit Gson - 如何将 JSON 字符串解析为 JSON 响应中 JSON 键的对象?

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:11:16 24 4
gpt4 key购买 nike

这是我的 JSON 响应:

{
"id": 2,
"name": "Test",
"content": "{\"type\": \"status\", \"text\": \"Lorem ipsum dummy text.\", \"id\": 1}"
}

这些是模型结构:

class TestModel {
public int id;
public String name;
public Content content;
}

class Content {
public int id;
public String status;
public String text;
}

我想使用 Retrofit 和 GsonConvertor 将内容的值直接解析到我的内容模型对象中。但目前,我将其解析为字符串值,而不是使用 Gson.fromJson() 转换为我的内容模型对象。有什么解决方案可以达到我的预期结果吗?

当我以前使用 GsonConverterFactory 解析它时,Retrofit 在 onFailure 方法中给出了回调,但有这个异常:

java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 4 column 19 path $.data[0].content

最佳答案

问题出在 JSON 响应上,它不在 correct JSON format 中. "content" 字段应该是一个对象,而不是字符串:

{
"id": 2,
"name": "Test",
"content": {
"type": "status",
"text": "Lorem ipsum dummy text.",
"id": 1
}
}

这将允许 gson.fromJson(response, TestModel.class) 或带有 GsonConverterFactoryRetroFit 将您的响应正确解析为相应的对象。


当然,这仅适用于您能够更改收到的 JSON 响应的情况。如果不是,请首先确保控制响应的人知道他们做的。如果没有任何变化,那么您应该能够通过将 TestModel 中的 content 更改为 String 来解决此问题:

class TestModel {
public int id;
public String name;
public String content;
}

class Content {
public int id;
public String type;
public String text;
}

然后分别解析每个对象:

TestModel testModel = gson.fromJson(response, TestModel.class);
Content content = gson.fromJson(testModel.content, Content.class);

如果无法更改响应,另一种选择是创建一个 TypeAdapter对于您的 Content 对象:

public class ContentAdapter extends TypeAdapter<Content> {

@Override
public void write(JsonWriter out, Content value) throws IOException {
// TODO: Writer implementation
}

@Override
public Content read(JsonReader in) throws IOException {
if(in.peek() != JsonToken.NULL) {
return fromJson(in.nextString());
} else {
in.nextNull();
return null;
}
}

}

然后将 TypeAdapter 添加到您的 GSON 实现中:

Gson gson = new GsonBuilder()
.registerTypeAdapter(Content.class, new ContentAdapter()).create();

关于Android - Retrofit Gson - 如何将 JSON 字符串解析为 JSON 响应中 JSON 键的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39342998/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com