关于转换:fastjson2中的JSONObject,转化
两种都试下:
旧:
<!-- fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.83</version>
</dependency>
导入:
import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject;
新:
pom:
<!-- Alibaba Fastjson -->
<dependency>
<groupId>com.alibaba.fastjson2</groupId>
<artifactId>fastjson2</artifactId>
<version>2.0.25</version>
</dependency>
导入:
import com.alibaba.fastjson2.JSON; import com.alibaba.fastjson2.JSONArray; import com.alibaba.fastjson2.JSONObject;
主要:
转成string:JSON.toJSONString(ClassObject)
把string转成一个对象:JSONObject.parseObject (String)、JSONObject.parse(String)
---------------------------------------------------------------------------------------
序列化、反序列化:

---------------------------------------------------------------------------------------------------------------------------------
string字符串转成json:
实例1:

实例2:
/**
* 判断波开放平台响应内容是否成功
*
* @param responseText 波开放平台响应内容
* @return boolean true:成功,false:失败
*/
public static NbcbResponse isSuccessOrExists(String responseText) {
NbcbResponse nbcbResponse = new NbcbResponse();
nbcbResponse.setSuccess(true);
JSONObject jsonObject = JSON.parseObject(responseText);
JSONArray retArray = jsonObject.getJSONObject("Data").getJSONObject("sysHead").getJSONArray("ret");
JSONObject retObject = (JSONObject) retArray.get(0);
String retCode = retObject.getString("retCode");
String retMsg = retObject.getString("retMsg");
boolean boolSuccess = StringUtils.equalsIgnoreCase(SDK_SUCCESS, retCode);
boolean boolExists = StringUtils.equalsIgnoreCase(SDK_EXISTS, retCode);
boolean boolInuses = StringUtils.equalsIgnoreCase(SDK_INUSE, retCode);
if (!(boolSuccess || boolExists || boolInuses)) {
log.error("波开放平台响应异常--->{}", responseText);
nbcbResponse.setRetMsg(retMsg);
nbcbResponse.setSuccess(false);
return nbcbResponse;
}
return nbcbResponse;
}
实体类转成String类型:

实例:
res:
{
"code":200,
"message":"success",
"data":{
"originGoodsId":"18823459",
"smartlinkGoodsId":1687039855971872769
},
"timestamp":1691056620021
}
//返回拿到res是个string
String res = new String(result.getBody(), StandardCharsets.UTF_8); // String转成Json对象,JSONObject.parseObject(string) 助记:解析为对象 JSONObject jsonObject = JSONObject.parseObject(res); // 从json对象中获取值,jsonObject.getString("") String code = jsonObject.getString("code"); log.error("code:{}", code); if ("200".equals(code)){ String data = jsonObject.getString("data"); String s = JSON.toJSONString(data); JSONObject dataJson = JSONObject.parseObject(data); FawGoods fawGoods = BeanUtils.convert(goodsInsertRequest, FawGoods.class); fawGoods.setSmartlinkGoodsId((Long) dataJson.get("smartlinkGoodsId")); // json对象中取值 jsonObject.get() fawGoods.setCreateTime((Date) jsonObject.get("timestamp"));
实例:
String reqBody;
Object reg = JSONObject.parse(reqBody)
实例:
解析成对象,用指定的实体接收:
MerchantPlaceOrderObResponse merchantPlaceOrderObResponse = JSONObject.parseObject(jsonObjectString, MerchantPlaceOrderObResponse.class);
---------------------------------------------------------------------------------------------------------------------------------
json string字符串、以及 json string字符串中取值
实例:
s.toString():
UsermInfoResponse[refrenceId=1197235249382576128, deptId=1386143669026902016, deptName='null', postId=1381730475239886848, postName='null', userAccount='18067413780', userPasswd='123123', userSalt='null', userName='刘先生', userHeader='https://jiangshen56.oss-cn-hangzhou.aliyuncs.com/freight/20220824/138827627892213350.png', userMobile='18667413789', userMark='=备注说明=', userAdmin=true, orgAdmin=true, userPrivate=false, userState=0, expireTime='null', loginAddr='12.246.52.231', loginTime='2023-03-08 14:24:27', loginNum=2, createTime='2022-08-25 09:14:34', updateTime='2023-03-08 14:24:27']
参数特征:最外层是[ ], 里面是逗号隔开,每个key和value是等于
String s1 = JSONUtils.toJSONString(s); //实际就是fastJson的SON.toJSONString()
结果转成了 json string字符串:
s1:{
"createTime":"2022-08-25 09:14:34",
"deptId":"1386143669026902016",
"deptName":"",
"expireTime":"",
"loginAddr":"12.246.52.231",
"loginNum":2,
"loginTime":"2023-03-08 14:24:27",
"orgAdmin":true,
"postId":"1381730475239886848",
"postName":"",
"refrenceId":"1197235249382576128",
"updateTime":"2023-03-08 14:24:27",
"userAccount":"18667413780",
"userAdmin":true,
"userHeader":"https://jiangshen56.oss-cn-hangzhou.aliyuncs.com/freight/20220824/138827627892213350.png",
"userMark":"=备注说明=",
"userMobile":"18667413789",
"userName":"刘先生",
"userPasswd":"123123",
"userPrivate":false,
"userSalt":"",
"userState":0
}
再获取s1 json string字符串中的key的值:
JSONObject jsonObject = JSONObject.parseObject(s1);
String str4 = jsonObject.getString("userPasswd");
log.error("str4:{}", str4);
结果:
str4:123123
上面实例参考自以下:
java Object获取属性_java object 获取属性_白snow的博客-CSDN博客
准备:
Ulog ulog = new Ulog();
ulog.setDesc("这是描述");
ulog.setTime((new Timer()).toString());
ulog.setName("日志");Object obj = ulog;
获取所有:
Method[] declaredMethods = obj.getClass().getDeclaredMethods();
for(Method method:declaredMethods){
if(method.getName().startsWith("get")){
Object o= null;
try {
o = method.invoke(obj);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
System.out.println("属性值get方法->"+o);
}
}
结果:

单个属性:
try {
Field name = obj.getClass().getDeclaredField("name");
name.setAccessible(true);
try {
System.out.println(name.get(obj).toString());
} catch (IllegalAccessException e) {
e.printStackTrace();
}
System.out.println();
} catch (NoSuchFieldException e) {
e.printStackTrace();
}
结果:

----------------------------------------------------------------------------------------------------------------
来源: pipicai96
作者:pipicai96
简介 这篇文章主要介绍了String转成JSON的实现以及相关的经验技巧,文章约6798字,浏览量292,点赞数3,值得参考!
String转成JSON
这个依赖很重要,我们将围绕fastjson中的JSONObject这个类来谈转换
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.15</version>
</dependency>
- String转成JSON
String json = "{"abc":"1","hahah":"2"}";
JSONObject jsonObject = JSONObject.parseObject(content);
一句话就能解决,非常便捷。
想要取出值,可以对`jsonObject`进行操作:
jsonObject.getString("abc");
结果为:`1`
- 将String转为list后转为JSON
List<String> list = new ArrayList<String>();
list.add("username");
list.add("age");
list.add("sex");
JSONArray array = new JSONArray();
array.add(list);
- 将String转为map后转为JSON
Map<String, String> map = new HashMap<String, String>();
map.put("abc", "abc");
map.put("def", "efg");
JSONArray array_test = new JSONArray();
array_test.add(map);
JSONObject jsonObject = JSONObject.fromObject(map);
特别注意:从JSONObject中取值,碰到了数字为key的时候,如
{
"userAnswer": {
"28568": {
"28552": {
"qId": "28552",
"order": "1",
"userScore": {
"score": 100
},
"answer": {
"28554": "28554"
},
"qScore": "100.0",
"qtype": "SingleChoice",
"sId": "28568"
}
}
},
"paperType": "1",
"paperOid": "28567",
"instanceId": 30823,
"remainingTime": -1,
"examOid": "28570"
}
获取“userAnswer”的value,再转成JSON,可仿照如下形式:
JSONObject userJson = JSONObject.parseObject(jsonObject.getString("userAnswer"));
但是想获取key"28568"就没这么容易了。直接像上述的写法,会报错。
我们浏览fastjson中的源码,总结下,应该如下写:
JSONObject question = (JSONObject) JSONObject.parseObject(section.getString("28568"), Object.class);
整体代码:
dao代码很容易,就不贴出来了。
package com.xiamenair.training.business.service;
import com.alibaba.fastjson.JSONObject;
import com.xiamenair.training.business.dao.elearningdao.ELearningExamInstanceDao;
import com.xiamenair.training.business.dao.masterdao.ELearningChoiceRecordDao;
import com.xiamenair.training.business.model.LasChoiceRecord;
import com.xiamenair.training.business.model.entity.elearning.LasExamInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import java.math.BigDecimal;
import java.sql.Blob;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.*;
@Service
public class ChoiceRecordService {
//查询数据Dao
@Autowired
private ELearningChoiceRecordDao eLearningChoiceRecordDao;
//转储数据Dao
@Autowired
private ELearningExamInstanceDao eLearningExamInstanceDao;
private ChoiceRecordService() {
}
private static class SingletonRecordInstance {
private static final LasChoiceRecord choiceRecord = new LasChoiceRecord();
}
public static LasChoiceRecord getMapInstance() {
return SingletonRecordInstance.choiceRecord;
}
private static SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
/**
* 定时任务,每天定时将E学网考试数据分析并转储
*
* @param : instanceIdList
* @return : void
* @author : 28370·皮育才
* @date : 2018/11/20
**/
@Scheduled(cron = "00 00 01 * * ?")
public void analysisChoiceRecord() {
//获取前一天的时间
Date date = new Date();
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(calendar.DATE, -1);
date = calendar.getTime();
String dateString = simpleDateFormat.format(date);
List<BigDecimal> instanceIdList = eLearningExamInstanceDao.findInstanceIdByFinishTime(dateString);
if(0 != instanceIdList.size()){
LasChoiceRecord lasChoiceRecord = getMapInstance();
instanceIdList.stream().forEach(instanceId -> {
Blob answerBlob = eLearningExamInstanceDao.findUserAnswer(instanceId);
Long userId = eLearningExamInstanceDao.findUserId(instanceId);
String content = null;
try {
content = new String(answerBlob.getBytes((long) 1, (int) answerBlob.length()));
} catch (SQLException e) {
e.printStackTrace();
System.out.println("SQLEXCEPTION:" + e);
}
JSONObject jsonObject = JSONObject.parseObject(content);
//针对本section的"公共"属性直接设置
lasChoiceRecord.setUserId(userId);
lasChoiceRecord.setPaperType(jsonObject.getString("paperType"));
lasChoiceRecord.setPaperId(jsonObject.getString("paperOid"));
lasChoiceRecord.setExamInstanceId(jsonObject.getString("instanceId"));
lasChoiceRecord.setRemainingTime(jsonObject.getString("remainingTime"));
lasChoiceRecord.setExamId(jsonObject.getString("examOid"));
//针对section中的题目进行细化循环拆分
JSONObject userJson = JSONObject.parseObject(jsonObject.getString("userAnswer"));
Set sectionSet = userJson.keySet();
Iterator<String> setIt = sectionSet.iterator();
analyzeAnswer(lasChoiceRecord, userJson, setIt);
});
}
}
private void analyzeAnswer(LasChoiceRecord lasChoiceRecord, JSONObject userJson, Iterator<String> setIt) {
while (setIt.hasNext()) {
//对每个question进行再次拆分出题目
JSONObject section = (JSONObject) JSONObject.parseObject(userJson.getString(setIt.next()), Object.class);
Set questionSet = section.keySet();
Iterator<String> queIt = questionSet.iterator();
while (queIt.hasNext()) {
JSONObject question = (JSONObject) JSONObject.parseObject(section.getString(queIt.next()), Object.class);
String userAnswer = question.getString("answer");
String userScore = question.getString("userScore");
lasChoiceRecord.setQuestionId(question.getString("qId"));
lasChoiceRecord.setRecordId(UUID.randomUUID().toString());
eLearningChoiceRecordDao.save(lasChoiceRecord);
}
}
}
}
以上就是本文的全部内容,希望对大家的学习有所帮助,本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。 原文地址:https://www.cnblogs.com/pipicai96/p/9986181.html
新一代开源开发者平台 GitCode,通过集成代码托管服务、代码仓库以及可信赖的开源组件库,让开发者可以在云端进行代码托管和开发。旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。
更多推荐



所有评论(0)