java输出json的键值对_【Java】返回的JSON对象是一串以数字开头的键值对,应该怎么接收呢...

比如通过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();

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值