比如通过GET方法向/sp/overrides/发送请求后,会返回一串JSON对象,如下:
{
"1": 0.5,
"2": 0.5,
"3": 0.5,
"4": 0.5
}
我用的是okHttp+moshi的方式取回得到的JSON对象,官方示例如下
private final OkHttpClient client \= new OkHttpClient();
private final Moshi moshi \= new Moshi.Builder().build();
private final JsonAdapter gistJsonAdapter \= moshi.adapter(Gist.class);
public void run() throws Exception {
Request request \= new Request.Builder()
.url("https://api.github.com/gists/c2a7c39532239ff261be")
.build();
try (Response response \= client.newCall(request).execute()) {
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
Gist gist \= gistJsonAdapter.fromJson(response.body().source());
for (Map.Entry entry : gist.files.entrySet()) {
System.out.println(entry.getKey());
System.out.println(entry.getValue().content);
}
}
}
static class Gist {
Map files;
}
static class GistFile {
String content;
}
请问对于这种直接返回一个数字的JSON对象应该怎么命名字段呢?
回答
随便命名,然后使用注解指定对应json的key
直接反序列化为Map
直接反序列化为json库内部节点
以jackson举例
public void testMap() throws IOException {
ObjectMapper objectMapper = new ObjectMapper();
String json = "{\\n" +
" \\"1\\": 0.5,\\n" +
" \\"2\\": 0.5,\\n" +
" \\"3\\": 0.5,\\n" +
" \\"4\\": 0.5\\n" +
"}";
Map map = objectMapper.readValue(json, Map.class);
System.out.println(map); // {1=0.5, 2=0.5, 3=0.5, 4=0.5}
}
public void testClass() throws IOException {
ObjectMapper objectMapper = new ObjectMapper();
String json = "{\\n" +
" \\"1\\": 0.5,\\n" +
" \\"2\\": 0.5,\\n" +
" \\"3\\": 0.5,\\n" +
" \\"4\\": 0.5\\n" +
"}";
SimpleTestModel m = objectMapper.readValue(json, SimpleTestModel.class);
System.out.println(m); // SimpleTestModel\[one=0.5, two=0.5, three=0.5, four=0.5\]
}
public static class SimpleTestModel {
@JsonProperty("1")
private Double one;
@JsonProperty("2")
private Double two;
@JsonProperty("3")
private Double three;
@JsonProperty("4")
private Double four;
// setter/getter...
@Override
public String toString() {
return new StringJoiner(", ", SimpleTestModel.class.getSimpleName() + "\[", "\]")
.add("one=" \+ one)
.add("two=" \+ two)
.add("three=" \+ three)
.add("four=" \+ four)
.toString();
}
}