分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 前端开发

json字符串和object之间的相互转化

发布时间:2023-09-06 02:01责任编辑:林大明关键词:jsjson
package asi;import java.util.ArrayList;import com.alibaba.fastjson.JSON;import com.alibaba.fastjson.JSONException;import com.alibaba.fastjson.JSONObject;public class TestJSONObject { private String name; private String sex; ?public String getName() { ?return name; } public void setName(String name) { ?this.name = name; } public String getSex() { ?return sex; } public void setSex(String sex) { ?this.sex = sex; } ?//json字符串转化为JSONObject类 public static JSONObject JSON2Object(String json){ ?JSONObject object=(JSONObject) JSONObject.parseObject(json); ?return object; } //json的list转化为ArrayList<JSONObject> public static ArrayList<JSONObject> JSONList2Object(String jsonList){ ?ArrayList<JSONObject> objectList=(ArrayList<JSONObject>) JSONObject.parseObject(jsonList,ArrayList.class); ?return objectList; } ?//object转化为json public static String Object2JSON(Object o){ ?return JSON.toJSONString(o); ??} ?public static void main(String[] args) { ???String json="{\"username\": \"Bonnie\",\"listData\": [{\"address\": \"石景山区\",\"street\": \"裕华路\"},{\"address\": \"海淀区\",\"street\": \"中山路\"}]}"; ?try{ ??//1、测试json转换成object ??JSONObject object=JSON2Object(json); ??String username=(String) object.get("username"); ??System.out.println(username); ?????String listData=String.valueOf(object.get("listData")); ????//(String) object.get("listData"); ??System.out.println(listData); ?????ArrayList<JSONObject> objectList=JSONList2Object(listData); ???for(int i=0;i<objectList.size();i++){ ??????System.out.println((String)((JSONObject) (objectList.toArray())[i]).get("address")); ???System.out.println((String)((JSONObject) (objectList.toArray())[i]).get("street")); ??} ??//2、测试object转化成json ??TestJSONObject t=new TestJSONObject(); ??t.setName("Bonnie"); ??t.setSex("female"); ?????System.out.println(Object2JSON(t)); ?}catch(JSONException e){ ??e.printStackTrace(); ?} ??????}}

注意要导入jar:

<dependency>
   <groupId>com.alibaba</groupId>
   <artifactId>fastjson</artifactId>
   <version>1.2.2</version>
  </dependency>

json字符串和object之间的相互转化

原文地址:https://www.cnblogs.com/BonnieWss/p/9224379.html

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved