String和JSON相互转换
·
1.JSON格式的字符串转对象
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
//String转对象
String message = "{\"name\":\"John\", \"age\":30, \"city\":\"New York\"}";
Person freeData = JSONObject.parseObject(message, new TypeReference<Person>(){});
2.对象转Json格式的字符串
JSON.toJSONString(faceStructuredData)
3.对象转JSONObject
//目标参数
JSONObject.parseObject(JSON.toJSONString(personNode));
4.将 json格式的字符串 转换 为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);
5.将JSONArray转换为 json格式的字符串:
方法一:
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();
6. 对象集合转JSONArray
//对象集合转JSONArray
List<Station> stations = List.of(new Station("北京站", "BJS"),new Station("上海站", "SHH"));
JSONArray jsonArray = JSONArray.parseArray(JSON.toJSONString(stations));
7.JSONObject和字符串的转换
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");
8.list和map转json格式的字符串
import com.alibaba.fastjson.JSON;
//list和map转json格式的字符串
List<Map<String,Object>> referTeamTradeTopList = new ArrayList<>();
HashMap<String, Object> map = new HashMap<>();
map.put("realname","zhangs");
map.put("productName","haike");
map.put("totalAmount",12);
referTeamTradeTopList.add(map);
//打印
String s1 = JSON.toJSONString(map);
//s1: {"totalAmount":12,"productName":"haike","realname":"zhangs"}
String s2 = JSON.toJSONString(referTeamTradeTopList);
//s2: [{"totalAmount":12,"productName":"haike","realname":"zhangs"}]
更多推荐
已为社区贡献1条内容
所有评论(0)