我有一个像这样的JSON:
{
"data":{
"mapping":[
{
"erp":"SYMIX",
"plant":"RY1",
"region":"NA"
},
{
"erp":"SAP",
"plant":"EXM",
"region":"ASIA"
}
]
}
}在此基础上,我得到了工厂的价值,我想得到erp的价值。例如,如果我获取RY1,则需要获取SYMIX。如何使用Java实现这一点?
发布于 2016-08-19 18:18:02
使用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“字符串替换为文件的路径即可。
发布于 2016-08-19 18:38:21
好的……我选择了一种非常直接的方法。试试这个:
public static Object searchArrayofObjects(JSONArray array, String searchByKey, String resultKey, Object searchObject) throws JSONException
{
Object result = null;
for (int i = 0; i < array.length(); i++)
{
JSONObject innerObject = array.getJSONObject(i);
if (innerObject.has(searchByKey) && innerObject.get(searchByKey).equals(searchObject))
{
result = innerObject.has(resultKey) ? innerObject.get(resultKey) : null;
break;
}
}
return result;
}现在调用searchArrayofObjects(映射,“工厂”,"erp","RY1"),它应该返回"SYMIX“。
很明显,我让它有点泛化了。但这是我认为的一般方法。
https://stackoverflow.com/questions/39035829
复制相似问题