如何使用改造将内部 json 字符串解析为嵌套 class
How to parse inner json string as nested class using retrofit
我以前使用过嵌套 类 的改造,但我正在尝试使用的当前 api 具有这样的结构:
请求正文:
{
"Id" : "a2",
"messageCode" : 1,
"bigNestedClass" : "{\"field1\":238,\"otherField\":246,\"ip\":\"10.255.130.154\",\"someOtherField\":15,\"Info\":1501069568}"
}
和类似的响应正文。
注意 bigNestedClass 是一个字符串。
我为请求和响应创建了不同的 pojo 类。但是,创建嵌套的 BigNestedClass 会使该字段填充为 JSON 对象,而不是 JSON 字符串。我在解析响应时也遇到了同样的问题。
我的问题:有没有一种改造方法可以编码,将嵌套的 类 解析为字符串?
我使用 Retrofit 2.0
我用gson(可以改)
和gson I would simply make this with TypeAdapter
。请参阅下面的 class:
public class MyTypeAdapter extends TypeAdapter<BigNestedClass> {
private Gson gson = new Gson();
@Override
public BigNestedClass read(JsonReader arg0) throws IOException {
// Get the string value and do kind of nested deserializing to an instance of
// BigNestedClass
return gson.fromJson(arg0.nextString(), BigNestedClass.class);
}
@Override
public void write(JsonWriter arg0, BigNestedClass arg1) throws IOException {
// Get the instance value and insted of normal serializing make the written
// value to be a string having escaped json
arg0.value(gson.toJson(arg1));
}
}
那么你只需要用gson注册MyTypeAdapter
,比如:
private Gson gson = new GsonBuilder()
.registerTypeAdapter(BigNestedClass.class, new MyTypeAdapter())
.create();
要retrofit使用它,您需要在创建它时做更多的事情:
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://api.example.com")
.addConverterFactory(GsonConverterFactory.create(gson))
.build();
我以前使用过嵌套 类 的改造,但我正在尝试使用的当前 api 具有这样的结构:
请求正文:
{
"Id" : "a2",
"messageCode" : 1,
"bigNestedClass" : "{\"field1\":238,\"otherField\":246,\"ip\":\"10.255.130.154\",\"someOtherField\":15,\"Info\":1501069568}"
}
和类似的响应正文。
注意 bigNestedClass 是一个字符串。
我为请求和响应创建了不同的 pojo 类。但是,创建嵌套的 BigNestedClass 会使该字段填充为 JSON 对象,而不是 JSON 字符串。我在解析响应时也遇到了同样的问题。
我的问题:有没有一种改造方法可以编码,将嵌套的 类 解析为字符串?
我使用 Retrofit 2.0
我用gson(可以改)
和gson I would simply make this with TypeAdapter
。请参阅下面的 class:
public class MyTypeAdapter extends TypeAdapter<BigNestedClass> {
private Gson gson = new Gson();
@Override
public BigNestedClass read(JsonReader arg0) throws IOException {
// Get the string value and do kind of nested deserializing to an instance of
// BigNestedClass
return gson.fromJson(arg0.nextString(), BigNestedClass.class);
}
@Override
public void write(JsonWriter arg0, BigNestedClass arg1) throws IOException {
// Get the instance value and insted of normal serializing make the written
// value to be a string having escaped json
arg0.value(gson.toJson(arg1));
}
}
那么你只需要用gson注册MyTypeAdapter
,比如:
private Gson gson = new GsonBuilder()
.registerTypeAdapter(BigNestedClass.class, new MyTypeAdapter())
.create();
要retrofit使用它,您需要在创建它时做更多的事情:
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://api.example.com")
.addConverterFactory(GsonConverterFactory.create(gson))
.build();