我的输入是JSON数据。它看起来像:
[
{
"shortName": "av",
"longName": "average",
"Color": "black",
"fromValue": "45",
"toValue": "59"
},
{
"shortName": "g",
"longName": "good",
"Color": "red",
"fromValue": "35",
"toValue": "68"
}
]
我需要将此数据转换为对象列表(PerfLevel
class)。我怎么能这样做?
答案 0 :(得分:1)
使用Jackson或GSON将JSON读取为List
或预期类型的数组。
杰克逊:
ObjectMapper mapper = new ObjectMapper(); // reuse if multiple calls
MyPOJO[] pojos = mapper.readValue(jsonSource, MyPojo[].class); // with `List`, need to use `TypeReference`
// or, if you do not have matching MyPOJO type:
List<Object> pojosAsMaps = mapper.readValue(jsonSource, List.class);
还有很多其他方法可以做到,比如阅读JSON树(JsonNode
)。
这完全取决于您是否可以轻松地将结构建模为Java类(如果是这样,最方便)。
答案 1 :(得分:0)
只需使用org.json。*包。
你可以在http://www.json.org/javadoc/org/json/package-summary.html JSONArray下查找它,JSONObject将是最有趣的代码片段。
你的JSON-Object也没有很好的格式化,你应该首先创建一个对象数组,如:
users : [{
"shortname" : "g",
"moreAttributes" : ""
}, {
"shortname" : "h",
"moreAttributes" : ""
}]
使用此数组结构,您可以在数组外添加对象信息。例如,错误消息。
现在您可以使用一些简单的方法访问您的json文件:
JSONObject jObj = //the json file you loaded
JSONArray jArr = jObj.getArray("users");
JSONObject jUser;
//at this point you can iterate over your array and get information via:
jUser = jArr.getJSONObject(1)
//now you can get all the information from the jUser object
//e.g.
jUser.getString("shortname");