【问题标题】:Getting key value using multiple keys in json using java [closed]使用java在json中使用多个键获取键值[关闭]
【发布时间】:2019-02-01 17:54:20
【问题描述】:

如何在java中使用多个键获取键值?

示例:我想提取 id=121 和 number=1 的名称

    [{
        "id": 121,
        "name": "Pants",
        "number": 1,
        "specification": ""
    },
    {
        "id": 121,
        "name": "color",
        "number": 2,
        "specification": ""
    }];

【问题讨论】:

  • 您是否已经拥有用于存储此类对象的 Java 数据类(具有 4 个字段)?
  • 你可以使用jsonPath通配符来提取这样的值,使用这个jsonPath:[?(@.id=='121' && @.number =='1')]

标签: java json rest rest-assured jsonpath


【解决方案1】:

如果您有专门的课程,例如:

class A {

    private String id;
    private String name;
    private int number;
    private String specification;

    //getters and setters method
}

然后你可以使用org.codehaus.jackson.map.ObjectMapper从json创建一个对象:

ObjectMapper mapper = new ObjectMapper();
A[] objects = mapper.readValue(jsonString, A[].class);

现在,@vader 提到了它,您可以使用过滤器方法来获得正确的值:

List<A> list = Arrays.stream(objects)
    .filter(obj -> obj.getId().equals("121") && obj.getNumber() == 1)
    .collect(Collectors.toList());

【讨论】:

    【解决方案2】:

    大概可以这样实现

    public class Main {
    
      public static void main(String[] args) throws JSONException {
    
        String json = "[{\"id\":121,\"name\":\"Pants\",\"number\":1,\"specification\":\"\"},{\"id\":121,\"name\":\"color\",\"number\":2,\"specification\":\"\"}]";
    
        JSONArray array = new JSONArray(json);
    
        final int ID = 121;
        final int NUMBER = 1;
    
        int size = array.length();
        for (int i = 0; i < size; i++) {
    
          final JSONObject obj = array.getJSONObject(i);
          final int id = obj.getInt("id");
          final int number = obj.getInt("number");
    
          if (id == ID && number == NUMBER) {
            System.out.println(obj.getString("name"));
          }
        }
    
      }
    }
    

    如果您想要更通用的东西,您可能希望将其反序列化为一个对象并使用 Java 8 集合方法。这是a link我从谷歌搜索中找到的。

    【讨论】:

      猜你喜欢
      • 2015-01-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-09
      • 2021-08-11
      • 1970-01-01
      • 2017-07-29
      • 1970-01-01
      相关资源
      最近更新 更多