我有一个像这样的json文件
[ {
"id":"serve-coffee",
"tags":[ {
"name": "@tag1", "line": 1
}
],
"description":"Coffee should not be served\n",
"name":"Serve coffee",
"keyword":"Feature",
"line":2,
"elements":[ {
"id": "serve-coffee;buy-last-coffee", "tags":[ {
"name": "@tag2", "line": 6
}
],
"description":"",
"name":"Buy last coffee",
"keyword":"Scenario",
"line":7,
"steps":[ {
"name": "there are 1 coffees left in the machine", "keyword": "Given ", "line": 8
}
,
{
"name": "I have deposited 1$", "keyword": "And ", "line": 9
}
],
"type":"scenario"
}
],
"uri":"src\/test\/resources\/traffic-remove-locations.feature"
}
]
Iam尝试将上面的json文件转换为JSONObject
。但是我遇到了类强制转换异常"java.lang.ClassCastException: org.json.simple.JSONArray cannot be cast to org.json.simple.JSONObject"
码
public static JSONObject convertFileToJSON(String fileName) throws ParseException {
// Read from File to String
JSONParser parser = new JSONParser();
JSONObject jsonObject = null;
try {
Object object = parser.parse(new FileReader(fileName));
jsonObject = (JSONObject) object; // Getting classCast Exception here.
} catch (FileNotFoundException e) {
} catch (IOException ioe) {
}
return jsonObject;
}
but when i changed the line
jsonObject = (JSONObject) object;
to
JSONArray jsonArray = (JSONObject)object
异常消失。
但是,如果我要转换为JSONArray
,那么我如何从id,tags
获取description
和JSONArray
等值。
请提供建议人
答案 0 :(得分:2)
尝试转换为JsonArray,然后借助JSON数组中的索引逐个转换对象。
Object object = parser.parse(new FileReader(fileName));
JsonArray jsonArr = (JsonArray) object; // Getting c
jsonObject jsonObj = jsonArr.get(0); //use index to access like a list
答案 1 :(得分:1)
您的JSON文件表示一个包含一个对象的数组。因此,如果这是一个Java数据结构,那么您可以有效地执行此操作:
ID
这显然不起作用,因为你无法将数组转换为单个对象。你真正想要做的是拉出数组的第一个元素。要继续Java示例,您需要执行
# INITIAL MERGE (CROSS-PRODUCT OF ALL ID PAIRINGS)
mdf = pd.merge(df1, df2, on=['ID'])
def f(row):
col = mdf[(mdf['ID'] == row['ID']) &
(mdf['date_time_x'] < row['date_time_y'])]['date_time_x'].max()
return col
# FILTER BY MATCHED DATES TO CONDITIONAL MAX
mdf = mdf[mdf['date_time_x'] == mdf.apply(f, axis=1)].reset_index(drop=True)
使用JSON内容,您的int[] arr = {5};
int i = (int)arr;
调用返回JSONArray,而不是JSONObject。所以你需要做这样的事情:
int[] arr = {5};
int i = (int)arr[0];
答案 2 :(得分:0)
我也面临同样的问题。我做了以下更改以使其工作。 下面是我的示例JSON。 {
"routes": [{
"startTime": 1520319414,
"routeInfo": [{
"routePart": 0,
"transType": "WALK",
"transDetails": {
"startLoc": {
"lat": 28.6434862,
"lon": 77.22542659999999
}
}
}, {
"routePart": 1,
"transType": "BUS",
"transDetails": {
"routeNumber": "307-U",
"interStopDetails": [{
"seq": 1,
"name": "test1",
"loc": {
"lat": 28.64302,
"lon": 77.2260367
},
"eta": 1520319600
}
]
}
}
],
"totalTime": 5742
}
]
}
解析解决方案: JSONObject obj =(JSONObject)jsonParser.parse(new FileReader(FilepathDummy));
JSONArray jsonRoutes= (JSONArray) obj.get("routes"); //Gives Main JSoN
JSONObject routeJsonObject = (JSONObject) jsonRoutes.get(0); // Route Array into JSON
JSONArray routeInfoArray = (JSONArray) routeJsonObject.get("routeInfo"); // RouteInfo Array
希望这可以解决您的问题。