本文讲述两种方法,使JSON对象转为Java类对象。基于FastJson1
对于以下的JSON对象:文章来源:https://www.toymoban.com/news/detail-692308.html
{
"message": "成功",
"code": 1,
"records": [
{
"id": 99309,
"brokerName": "",
"fileType": "协议",
"effectiveDate": "20220818",
"createDate": "20220812"
},
{
"id": 99308,
"brokerName": "",
"fileType": "合同",
"effectiveDate": "20220812",
"createDate": "20220812"
}
]
}
假设以上的JSON对象已通过toJSONString()方法转为String,那么有两种方法可以将其转为Java类对象,前提是已定义一个YourClass类,其成员变量可以容纳以上records内的各个字段,两种转换方法如下:文章来源地址https://www.toymoban.com/news/detail-692308.html
// 方法一:
JSONObject jsonResult = JSON.parseObject(result); // result是以上JSON对象转成的String
String code = jsonResult.getString("code");
String message = jsonResult.getString("message");
JSONArray arrayData = jsonResult.getJSONArray("records");
for (Object obj : arrayData) {
JSONObject jsonObj = (JSONObject) obj;
YourClass agreement = JSON.toJavaObject(jsonObj, YourClass.class);
agreement.setFilePath(concatYourClassPath(agreement.getId()));
logger.info("单个对象:" + agreement.toString());
}
// 方法二:
JSONObject jsonResult = JSON.parseObject(result);
String code = jsonResult.getString("code");
String message = jsonResult.getString("message");
JSONArray jsonArray = jsonResult.getJSONArray("records");
List<YourClass> list = jsonArray.toJavaList(YourClass.class);
for (YourClass elem : list) {
logger.info("单个对象:" + elem.toString());
}
到了这里,关于JSON对象转为Java类对象的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!