当前位置:   article > 正文

关于转换:fastjson2中的JSONObject,转化_fastjson object转jsonobject

fastjson object转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;
 

获取所有:

  1. Method[] declaredMethods = obj.getClass().getDeclaredMethods();
  2. for(Method method:declaredMethods){
  3. if(method.getName().startsWith("get")){
  4. Object o= null;
  5. try {
  6. o = method.invoke(obj);
  7. } catch (IllegalAccessException e) {
  8. e.printStackTrace();
  9. } catch (InvocationTargetException e) {
  10. e.printStackTrace();
  11. }
  12. System.out.println("属性值get方法->"+o);
  13. }
  14. }

结果:

单个属性:

  1. try {
  2. Field name = obj.getClass().getDeclaredField("name");
  3. name.setAccessible(true);
  4. try {
  5. System.out.println(name.get(obj).toString());
  6. } catch (IllegalAccessException e) {
  7. e.printStackTrace();
  8. }
  9. System.out.println();
  10. } catch (NoSuchFieldException e) {
  11. e.printStackTrace();
  12. }

 结果:


----------------------------------------------------------------------------------------------------------------

来源: pipicai96

String转成JSON的实现_136.la

作者:pipicai96

简介  这篇文章主要介绍了String转成JSON的实现以及相关的经验技巧,文章约6798字,浏览量292,点赞数3,值得参考!

String转成JSON

这个依赖很重要,我们将围绕fastjson中的JSONObject这个类来谈转换

  1. <dependency>
  2. <groupId>com.alibaba</groupId>
  3. <artifactId>fastjson</artifactId>
  4. <version>1.2.15</version>
  5. </dependency>
  1. String转成JSON
  1. String json = "{"abc":"1","hahah":"2"}";
  2. JSONObject jsonObject = JSONObject.parseObject(content);
  1. 一句话就能解决,非常便捷。
  2. 想要取出值,可以对`jsonObject`进行操作:
jsonObject.getString("abc");
结果为:`1`
  1. 将String转为list后转为JSON
  1. List<String> list = new ArrayList<String>(); 
  2. list.add("username"); 
  3. list.add("age"); 
  4. list.add("sex"); 
  5. JSONArray array = new JSONArray(); 
  6. array.add(list);   
  1. 将String转为map后转为JSON
  1. Map<String, String> map = new HashMap<String, String>();
  2.     map.put("abc", "abc");
  3. map.put("def", "efg");
  4. JSONArray array_test = new JSONArray();
  5. array_test.add(map);
  6.     JSONObject jsonObject = JSONObject.fromObject(map);

特别注意:从JSONObject中取值,碰到了数字为key的时候,如

  1. {
  2. "userAnswer": {
  3. "28568": {
  4. "28552": {
  5. "qId": "28552",
  6. "order": "1",
  7. "userScore": {
  8. "score": 100
  9. },
  10. "answer": {
  11. "28554": "28554"
  12. },
  13. "qScore": "100.0",
  14. "qtype": "SingleChoice",
  15. "sId": "28568"
  16. }
  17. }
  18. },
  19. "paperType": "1",
  20. "paperOid": "28567",
  21. "instanceId": 30823,
  22. "remainingTime": -1,
  23. "examOid": "28570"
  24. }
获取“userAnswer”的value,再转成JSON,可仿照如下形式:
JSONObject userJson = JSONObject.parseObject(jsonObject.getString("userAnswer"));
  1. 但是想获取key"28568"就没这么容易了。直接像上述的写法,会报错。
  2. 我们浏览fastjson中的源码,总结下,应该如下写:
JSONObject question = (JSONObject) JSONObject.parseObject(section.getString("28568"), Object.class);

整体代码:

  1. dao代码很容易,就不贴出来了。
  2. package com.xiamenair.training.business.service;
  3. import com.alibaba.fastjson.JSONObject;
  4. import com.xiamenair.training.business.dao.elearningdao.ELearningExamInstanceDao;
  5. import com.xiamenair.training.business.dao.masterdao.ELearningChoiceRecordDao;
  6. import com.xiamenair.training.business.model.LasChoiceRecord;
  7. import com.xiamenair.training.business.model.entity.elearning.LasExamInstance;
  8. import org.springframework.beans.factory.annotation.Autowired;
  9. import org.springframework.scheduling.annotation.Scheduled;
  10. import org.springframework.stereotype.Service;
  11. import java.math.BigDecimal;
  12. import java.sql.Blob;
  13. import java.sql.SQLException;
  14. import java.text.SimpleDateFormat;
  15. import java.util.*;
  16. @Service
  17. public class ChoiceRecordService {
  18. //查询数据Dao
  19. @Autowired
  20. private ELearningChoiceRecordDao eLearningChoiceRecordDao;
  21. //转储数据Dao
  22. @Autowired
  23. private ELearningExamInstanceDao eLearningExamInstanceDao;
  24. private ChoiceRecordService() {
  25. }
  26. private static class SingletonRecordInstance {
  27. private static final LasChoiceRecord choiceRecord = new LasChoiceRecord();
  28. }
  29. public static LasChoiceRecord getMapInstance() {
  30. return SingletonRecordInstance.choiceRecord;
  31. }
  32. private static SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
  33. /**
  34. * 定时任务,每天定时将E学网考试数据分析并转储
  35. *
  36. * @param : instanceIdList
  37. * @return : void
  38. * @author : 28370·皮育才
  39. * @date : 2018/11/20
  40. **/
  41. @Scheduled(cron = "00 00 01 * * ?")
  42. public void analysisChoiceRecord() {
  43. //获取前一天的时间
  44. Date date = new Date();
  45. Calendar calendar = Calendar.getInstance();
  46. calendar.setTime(date);
  47. calendar.add(calendar.DATE, -1);
  48. date = calendar.getTime();
  49. String dateString = simpleDateFormat.format(date);
  50. List<BigDecimal> instanceIdList = eLearningExamInstanceDao.findInstanceIdByFinishTime(dateString);
  51. if(0 != instanceIdList.size()){
  52. LasChoiceRecord lasChoiceRecord = getMapInstance();
  53. instanceIdList.stream().forEach(instanceId -> {
  54. Blob answerBlob = eLearningExamInstanceDao.findUserAnswer(instanceId);
  55. Long userId = eLearningExamInstanceDao.findUserId(instanceId);
  56. String content = null;
  57. try {
  58. content = new String(answerBlob.getBytes((long) 1, (int) answerBlob.length()));
  59. } catch (SQLException e) {
  60. e.printStackTrace();
  61. System.out.println("SQLEXCEPTION:" + e);
  62. }
  63. JSONObject jsonObject = JSONObject.parseObject(content);
  64. //针对本section"公共"属性直接设置
  65. lasChoiceRecord.setUserId(userId);
  66. lasChoiceRecord.setPaperType(jsonObject.getString("paperType"));
  67. lasChoiceRecord.setPaperId(jsonObject.getString("paperOid"));
  68. lasChoiceRecord.setExamInstanceId(jsonObject.getString("instanceId"));
  69. lasChoiceRecord.setRemainingTime(jsonObject.getString("remainingTime"));
  70. lasChoiceRecord.setExamId(jsonObject.getString("examOid"));
  71. //针对section中的题目进行细化循环拆分
  72. JSONObject userJson = JSONObject.parseObject(jsonObject.getString("userAnswer"));
  73. Set sectionSet = userJson.keySet();
  74. Iterator<String> setIt = sectionSet.iterator();
  75. analyzeAnswer(lasChoiceRecord, userJson, setIt);
  76. });
  77. }
  78. }
  79. private void analyzeAnswer(LasChoiceRecord lasChoiceRecord, JSONObject userJson, Iterator<String> setIt) {
  80. while (setIt.hasNext()) {
  81. //对每个question进行再次拆分出题目
  82. JSONObject section = (JSONObject) JSONObject.parseObject(userJson.getString(setIt.next()), Object.class);
  83. Set questionSet = section.keySet();
  84. Iterator<String> queIt = questionSet.iterator();
  85. while (queIt.hasNext()) {
  86. JSONObject question = (JSONObject) JSONObject.parseObject(section.getString(queIt.next()), Object.class);
  87. String userAnswer = question.getString("answer");
  88. String userScore = question.getString("userScore");
  89. lasChoiceRecord.setQuestionId(question.getString("qId"));
  90. lasChoiceRecord.setRecordId(UUID.randomUUID().toString());
  91. eLearningChoiceRecordDao.save(lasChoiceRecord);
  92. }
  93. }
  94. }
  95. }

以上就是本文的全部内容,希望对大家的学习有所帮助,本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。 原文地址:https://www.cnblogs.com/pipicai96/p/9986181.html

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/盐析白兔/article/detail/532679
推荐阅读
相关标签
  

闽ICP备14008679号