java - 如何根据条件获取 JSON 值

标签 java json

我有一个像这样的 JSON:

{
   "data":{
      "mapping":[
         {
            "erp":"SYMIX",
            "plant":"RY1",
            "region":"NA"
         },
         {
            "erp":"SAP",
            "plant":"EXM",
            "region":"ASIA"
         }
      ]
   }
}

我在此基础上得到了 plant 的值,我想得到 erp 的值。 就像如果我得到 RY1 SYMIX 需要获取一样。我怎样才能使用Java实现这一点

最佳答案

使用 jayway 库可以轻松完成:

    <dependency>
        <groupId>com.jayway.jsonpath</groupId>
        <artifactId>json-path</artifactId>
    </dependency>

示例:

import java.util.List;

import com.jayway.jsonpath.JsonPath;

public class TestJson {
 private static final String JSON = "{\"data\":{\"mapping\":[{\"erp\":\"SYMIX\",\"plant\":\"RY1\",\"region\":\"NA\"},{\"erp\":\"SAP\",\"plant\":\"EXM\",\"region\":\"ASIA\"}]}}";

 public static void main(String[] args) {
     String erp = getErp("RY1");
     System.out.println(erp);
 }

 private static String getErp(String plant) {
     List<String> values = JsonPath.read(JSON, String.format("$.data.mapping.[?(@.plant==%s)].erp", plant));
     return values.isEmpty() ? null : values.get(0);
 }
}

输出为:SYMIX

<小时/>

更新:

好的,这里是从文件中读取的版本:

import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;

import com.jayway.jsonpath.JsonPath;

public class TestJson {
    public static void main(String[] args) throws Exception {
        String pathToFile = "file.json";
        String plant = "RY1";

        File file = openFile(pathToFile);
        String erp = readErpFromFile(file, plant);
        System.out.println("Erp: " + erp);
    }

    private static String readErpFromFile(File file, String plant) throws Exception {
        List<String> values = JsonPath.read(file, String.format("$.data.mapping.[?(@.plant==%s)].erp", plant));
        return values.isEmpty() ? null : values.get(0);
    }

    private static File openFile(String strPath) throws IOException {
        Path path = Paths.get(strPath);
        System.out.println("Trying to read file: " + path.toAbsolutePath().toString());
        return path.toFile();
    }
}

只需将“file.json”字符串替换为文件的路径即可。

关于java - 如何根据条件获取 JSON 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39035829/

相关文章:

javascript - 循环内的 json 对象修改不起作用

JSONLint 验证错误--预期 EOF

java - 生成 Java 文件的导入列表

java - {Filter}ing 是否比 Lucene 中的 {Query}ing 更快?

java - 正则表达式匹配非前面的字符并匹配后面的字符

javascript - JSON 分页响应 javascript

java - 检测病毒扫描程序

java - 为什么允许抽象类 "DocumentBuilderFactory"实例化新实例

java - Jackson 反序列化 - 空对象引用上的 JsonMappingException

c# - 如何从 JToken 填充现有对象(使用 Newtonsoft.Json)?