使用Java在JSON中使用多个键获取键值

时间:2019-02-01 17:54:21

标签: java json rest rest-assured jsonpath

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

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

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

2 个答案:

答案 0 :(得分:4)

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

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());

答案 1 :(得分:0)

这大概可以做到

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收集方法。这是我在Google搜索中找到的a link