String和JSON相互转换
•
数据库
1.对象转JSONStr
JSON.toJSONString(faceStructuredData)
1.对象转JSONObject
//目标参数
@ApiModelProperty("人员节点数据")
private JSONObject personDetail;
//转换过程 (personNode 是一个对象)
record.setPersonDetail(JSONObject.parseObject(JSON.toJSONString(personNode)));
2.将String转换为JSONArray:
方法一:
String str = "[{\"name\":\"Alice\",\"age\":20},{\"name\":\"Bob\",\"age\":30}]";
JSONArray jsonArray = JSON.parseArray(str);
方法二:
String jsonString = "[\"value1\",\"value2\"]"; JSONArray jsonArray = new JSONArray(jsonString);
3.将JSONArray转换为String:
方法一:
JSONArray jsonArray = new JSONArray();
JSONObject obj1 = new JSONObject();
obj1.put("name", "Alice");
obj1.put("age", 20);
JSONObject obj2 = new JSONObject();
obj2.put("name", "Bob");
obj2.put("age", 30);
jsonArray.add(obj1);
jsonArray.add(obj2);
String str = jsonArray.toJSONString();
方法二:
JSONArray jsonArray = new JSONArray();
jsonArray.put("value1");
jsonArray.put("value2");
String jsonString = jsonArray.toString();
4.fastjson和字符串的转换
import com.alibaba.fastjson.JSONObject;
#存入属性
JSONObject jsonObject = new JSONObject();
jsonObject.put("name", "John");
jsonObject.put("age", 30);
String myStr = jsonObject.toJSONString();
#取出属性
JSONObject jsonObject1 = JSON.parseObject(myStr);
String name = jsonObject1.getString("name");
本文来自网络,不代表协通编程立场,如若转载,请注明出处:https://www.net2asp.com/3b0e5784ba.html
