我正在尝试解析JSON并根据输入键拉取值。JSON结构并不相同,下面是示例JSON结构,JSON以[]开头和结尾,有时{}
[
{
"id": "0001",
"type": "donut",
"name": "Cake",
"ppu": 0.55,
"days": {
"weekdays": "Friday",
"weekends": "Sunday",
},
"batters": {
"batter": [
{
"id": "1001",
"type": "Regular"
},
{
"id": "1002",
"type": "Chocolate"
},
]
},
"topping": [
{
"id": "5001",
"type": "None"
},
{
"id": "5002",
"type": "Glazed"
},
]
}
]
{
"id": "0001",
"type": "donut",
"name": "Cake",
"ppu": 0.55,
"days": {
"weekdays": "Friday",
"weekends": "Sunday",
},
"batters": {
"batter": [
{
"id": "1001",
"type": "Regular"
},
{
"id": "1002",
"type": "Chocolate"
},
]
},
"topping": [
{
"id": "5001",
"type": "None"
},
{
"id": "5002",
"type": "Glazed"
},
]
}
我尝试以下代码
import org.json.simple.*;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
public static void main(String[] args) throws IOException, Exception {
File InputFolder = new File(System.getProperty("user.dir") + "//Files//new.json");
JsonElementFromFile(InputFolder,"name");
}
public static void JsonElementFromFile(File FilePath, String key) throws IOException, Exception {
JSONParser parser = new JSONParser();
FileReader reader = new FileReader(FilePath);
JSONArray obj = (JSONArray) parser.parse(reader);
for (Object o : obj) {
JSONObject json = (JSONObject) o;
String jsonKeyValue = (String)json.get(key).toString();
System.out.println(key + " : " + jsonKeyValue); }
}
1.上述代码在JSON数据以"["开头时有效,但在以"{"开头时无效,不管我应该能够获取值的任何结构
1.我能够从第一个对象键"id","type","name","ppu"只拉值,但当我通过键作为"days.weekdays"它不是拉.即使我有更多的数组和objectsi应该能够拉只是通过键的路径,例如:"击球手.击球手[0]. id"或"击球手.击球手[1]. type"**
1.基本上,我正在寻找可重用的代码,以拉值的基础上传递的关键字,不想硬编码任何值从JSON。
谢谢
1条答案
按热度按时间dfty9e191#
如果不想硬编码不同的JSON结构,解决方案是使用JSON查询库。
https://github.com/octomix/josson
反序列化数组
反序列化对象
查询