json在java中按键选择多个值

时间:2017-10-05 08:51:50

标签: java json

我有一个如下所示的json

[{
    "D_Table_Name": "BUILDING",
    "S_Table_Name": "View1",
    "S_Data_Field_Name": "USECD",
    "D_Field_Name": "Description",
    "MappingCode": "FIELD"
  },
  {
    "D_Table_Name": "BUILDING",
    "S_Table_Name": "View1",
    "S_Data_Field_Name": "USECD",
    "D_Field_Name": "StndCode",
    "MappingCode": "FIELD"
  },
  {
    "D_Table_Name": "asdasd",
    "S_Table_Name": "View1",
    "S_Data_Field_Name": "qwew",
    "D_Field_Name": "ijhbgr4",
    "MappingCode": "FIELD"
  },
  {
    "D_Table_Name": "qwsdcv",
    "S_Table_Name": "View1",
    "S_Data_Field_Name": "kjmnbv",
    "D_Field_Name": "dszfs",
    "MappingCode": "FIELD"
  }]

如何获取密钥S_Table_Name

的所有值

4 个答案:

答案 0 :(得分:1)

假设您正在使用任何特定库将JSON字符串转换为Object,请假设我正在使用GSON

List<String> sTableNameValues = new ArrayList<>();
List<Map<String,String>> input = new GSON.fromJSON(inputJSONString);
for(Map.Entry<String,String> entry: input.entrySet()){
   if(entry.getKey().equals("S_Table_Name")){
      sTableNameValues.add(entry.getValue());
   }
}
// Now all your S_Table_Name values are inside your list.

答案 1 :(得分:1)

使用jackson库:

ObjectMapper mapper = new ObjectMapper();
JsonNode array = mapper.readValue(yourJson, JsonNode.class);

获取价值观:

for (int i = 0; i < array.size(); i++) {
  String reportKey = array.get(i).get("S_Table_Name").textValue();
  System.out.println(reportKey);
}

答案 2 :(得分:0)

json-path这样的东西应该有所帮助。在您的情况下,表达式应该类似于:

$[*].S_Table_Name

答案 3 :(得分:0)

您也可以使用org.json.JSONObject库。请参阅以下代码:

String response = "[{\"D_Table_Name\": \"BUILDING\",\"S_Table_Name\": \"View1\",\"S_Data_Field_Name\": \"USECD\",\"D_Field_Name\": \"Description\",\"MappingCode\": \"FIELD\"},{\"D_Table_Name\": \"BUILDING\",\"S_Table_Name\": \"View1\",\"S_Data_Field_Name\": \"USECD\",\"D_Field_Name\": \"StndCode\",\"MappingCode\": \"FIELD\"},{\"D_Table_Name\": \"asdasd\",\t\t\"S_Table_Name\": \"View1\",\"S_Data_Field_Name\": \"qwew\",\"D_Field_Name\": \"ijhbgr4\",\"MappingCode\": \"FIELD\"},{\"D_Table_Name\": \"qwsdcv\",\"S_Table_Name\": \"View1\",\t\"S_Data_Field_Name\": \"kjmnbv\",\"D_Field_Name\": \"dszfs\",\"MappingCode\": \"FIELD\"}]";

    JSONArray responseArray = new JSONArray(response);

    if (responseArray.length() > 0) {
        for (int i = 0; i < responseArray.length(); i++) {
            JSONObject responseObject = responseArray.getJSONObject(i);
            if (responseObject.has("S_Table_Name")) {
                String S_Table_Name = responseObject.getString("S_Table_Name");
                System.out.println(S_Table_Name);
            }
        }
    }