我有一个像这样的 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/