返回的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<Gist\> 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<String, GistFile\> entry : gist.files.entrySet()) {
        System.out.println(entry.getKey());
        System.out.println(entry.getValue().content);
      }
    }
  }

  static class Gist {
    Map<String, GistFile\> files;
  }

  static class GistFile {
    String content;
  }

请问对于这种直接返回一个数字的JSON对象应该怎么命名字段呢?

阅读 3.3k
1 个回答
  1. 随便命名,然后使用注解指定对应json的key
  2. 直接反序列化为Map
  3. 直接反序列化为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<String, Object> 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();  
    }  
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题