Java工具-JsonObject&JsonArray/Object/String相互转换(FastJson)

ゝ一纸荒年。 2023-02-23 09:27 32阅读 0赞

前言

之前处理Json类型字符串. 对于相关细节有些疏忽了(Spark SQL 导入JSON文件).
借此机会将Json类型字符串全部梳理一遍.


Maven 引用

  1. <dependencies>
  2. <dependency>
  3. <groupId>com.alibaba</groupId>
  4. <artifactId>fastjson</artifactId>
  5. <version>1.2.4</version>
  6. </dependency>
  7. <dependency>
  8. <groupId>junit</groupId>
  9. <artifactId>junit</artifactId>
  10. <version>4.12</version>
  11. <scope>test</scope>
  12. </dependency>
  13. </dependencies>

Json 相关表示类型

  • Object对象(单个)

    {“name”:”sean”,”age”:18,”sex”:”male”}

  • Object对象(多个)

    {“name”:”sean”,”age”:18,”sex”:”male”},
    {“name”:”coal”,”age”:18,”sex”:”male”}

  • 数组&List

    [{“age”:18,”sex”:”male”,”name”:”Sean”},{“age”:18,”sex”:”male”,”name”:”bruce”},{“age”:18,”sex”:”male”,”name”:”gogogo”}]

  • Map

    {“sean”:”hello”,”bruce”:”gogogo”}

  • 复杂数据类型(混合类)

    {“list”:[“ListValue1”,”ListValue2”],”map”:{“map2”:”mapValue2”,”map1”:”mapValue1”},”name”:”sean”,”stringArray”:[“stringValue1”,”stringValue2”]}


相关POJO

  • People

    import com.alibaba.fastjson.annotation.JSONField;

    public class People {

    1. @JSONField(ordinal = 1)
    2. public String name;
    3. // @JSONField()
    4. public Integer age;
    5. public String sex;
    6. public People() {}
    7. public People(String name,Integer age,String sex) {
    8. this.name = name;
    9. this.age = age;
    10. this.sex = sex;
    11. }
    12. public String getName() {
    13. return name;
    14. }
    15. public void setName(String name) {
    16. this.name = name;
    17. }
    18. public Integer getAge() {
    19. return age;
    20. }
    21. public void setAge(Integer age) {
    22. this.age = age;
    23. }
    24. public String getSex() {
    25. return sex;
    26. }
    27. public void setSex(String sex) {
    28. this.sex = sex;
    29. }

    }

  • ComplexPeople

    package com.yanxml.arsenal.java.json.pojo;

    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;

    public class ComplexPeople {

    1. String name;
    2. Map<String ,String> map;
    3. List<String> list;
    4. String [] stringArray;
  1. public ComplexPeople() {
  2. name = "sean";
  3. // Map
  4. map = new HashMap();
  5. map.put("map1", "mapValue1");
  6. map.put("map2", "mapValue2");
  7. // List
  8. list = new ArrayList<String>();
  9. list.add("ListValue1");
  10. list.add("ListValue2");
  11. stringArray = new String[2];
  12. stringArray[0]="stringValue1";
  13. stringArray[1]="stringValue2";
  14. }
  15. public String getName() {
  16. return name;
  17. }
  18. public void setName(String name) {
  19. this.name = name;
  20. }
  21. public Map<String, String> getMap() {
  22. return map;
  23. }
  24. public void setMap(Map<String, String> map) {
  25. this.map = map;
  26. }
  27. public List<String> getList() {
  28. return list;
  29. }
  30. public void setList(List<String> list) {
  31. this.list = list;
  32. }
  33. public String[] getStringArray() {
  34. return stringArray;
  35. }
  36. public void setStringArray(String[] stringArray) {
  37. this.stringArray = stringArray;
  38. }
  39. }

转换操作

  • Object 相关

    //@Test

    1. public void testForObject() {
    2. // 转换为 JSONOBJECT
    3. String peopleJsonString = "{\"name\":\"sean\",\"age\":18,\"sex\":\"male\"}";
    4. JSONObject jsonObject = JSONObject.parseObject(peopleJsonString);
    5. String peopleName = (String)jsonObject.get("name");
    6. Integer peopleAge = (Integer)jsonObject.get("age");
    7. System.out.println("name:"+peopleName+" age:"+peopleAge);
    8. // 转换为Object
    9. People people = JSONObject.parseObject(peopleJsonString,People.class);
    10. System.out.println(people.getName()+" / "+people.getAge());
    11. }
    12. //@Test
    13. public void testForObjectToJson() {
    14. People people = new People("Sean", 18, "male");
    15. // 不指定顺序 {"age":18,"name":"Sean","sex":"male"}
    16. String peopleJsonStr = JSONObject.toJSONString(people);
    17. System.out.println(peopleJsonStr);
    18. // 指定顺序类型 - @JSONField(ordinal = 1)
    19. // Object 转换为Jsonobject
    20. JSONObject object = (JSONObject) JSONObject.toJSON(people);
    21. System.out.println(object.get("name")+" : "+object.get("age"));
    22. }
  • 数组相关

    //@Test

    1. public void testForArray() {
    2. // 转换为JsonObject
    3. String arrayJson = "[{\"age\":18,\"sex\":\"male\",\"name\":\"Sean\"},{\"age\":18,\"sex\":\"male\",\"name\":\"bruce\"},{\"age\":18,\"sex\":\"male\",\"name\":\"gogogo\"}]\n";
    4. JSONArray jsonArray = JSONObject.parseArray(arrayJson);
    5. System.out.println(jsonArray.get(1).toString());
    6. // 转换为ObjectArray
    7. List<People> peopleList = JSON.parseArray(arrayJson, People.class);
    8. People[] peopleArray = (People[])peopleList.toArray();
    9. // Array转变为List
    10. List<String> arrayList = Arrays.asList(new String[] {""});
    11. }
  1. //@Test
  2. public void testForArrayJson() {
  3. People[] peopleArray = new People[3];
  4. peopleArray[0] = new People("Sean",18,"male");
  5. peopleArray[1] = new People("bruce",18,"male");
  6. peopleArray[2] = new People("gogogo",18,"male");
  7. String jsonString = JSONObject.toJSONString(peopleArray);
  8. System.out.println(jsonString);
  9. }
  • Map相关

    // Map数据类型转换

    1. //@Test
    2. public void testForMap() {
    3. String mapString = "{\"sean\":\"hello\",\"bruce\":\"gogogo\"}";
    4. JSONObject jsonObject = JSONObject.parseObject(mapString);
    5. Map<String,Object> map = (Map<String, Object>)jsonObject;
    6. }
  1. //@Test
  2. public void testForMapJson() {
  3. Map<String,String> map = new HashMap();
  4. map.put("sean", "hello");
  5. map.put("bruce", "gogogo");
  6. String jsonString = JSONObject.toJSONString(map);
  7. System.out.println(jsonString);
  8. }
  • 复杂数据类型相关

    // 复杂数据类型转换为JsonString字符串

    1. //@Test
    2. public void testForComplexObject() {
    3. String jsonString = JSONObject.toJSONString(new ComplexPeople());
    4. System.out.println(jsonString);
    5. JSONObject jsonObject = (JSONObject) JSONObject.toJSON(new ComplexPeople());
    6. }
    7. @Test
    8. public void testForComplexJson() {
    9. String jsonString ="{\"list\":[\"ListValue1\",\"ListValue2\"],\"map\":{\"map2\":\"mapValue2\",\"map1\":\"mapValue1\"},\"name\":\"sean\",\"stringArray\":[\"stringValue1\",\"stringValue2\"]}";
    10. // 转换为ComplexPeople实体类
    11. ComplexPeople complexPeople = JSONObject.parseObject(jsonString,ComplexPeople.class);
    12. System.out.println("map2:"+complexPeople.getMap().get("map2"));
    13. System.out.println("stringArray:"+complexPeople.getStringArray().toString());
  1. // 转换为JsonObject
  2. JSONObject jsonObject = JSONObject.parseObject(jsonString);
  3. }

注意事项

  • 所有需要Json转换的字段必须设置public, 或者设置public接口get/set方法.
  • 忽略某些字段 & 输出Json顺序. 可以使用框架的@JsonField实现. @JSONField(ordinal = 1)/@JSONField(serialize = false)
  • 其他Json标签.
    在这里插入图片描述
  • Json必须有可以访问的缺省构造函数. 否则报告如下异常.

    com.alibaba.fastjson.JSONException: default constructor not found. class com.yanxml.arsenal.java.json.pojo.People

    1. at com.alibaba.fastjson.util.DeserializeBeanInfo.computeSetters(DeserializeBeanInfo.java:182)
    2. at com.alibaba.fastjson.parser.ParserConfig.createJavaBeanDeserializer(ParserConfig.java:469)
    3. at com.alibaba.fastjson.parser.ParserConfig.getDeserializer(ParserConfig.java:427)
    4. at com.alibaba.fastjson.parser.ParserConfig.getDeserializer(ParserConfig.java:348)
    5. at com.alibaba.fastjson.parser.DefaultJSONParser.parseObject(DefaultJSONParser.java:548)
    6. at com.alibaba.fastjson.JSON.parseObject(JSON.java:250)
    7. at com.alibaba.fastjson.JSON.parseObject(JSON.java:226)
    8. at com.alibaba.fastjson.JSON.parseObject(JSON.java:185)
    9. at com.alibaba.fastjson.JSON.parseObject(JSON.java:303

Reference

[1]. JAVA中使用alibaba fastjson实现JSONObject、Object、Json字符串的转换
[2]. 阿里FastJson常见类型解析
[3]. 使用FastJSON 对Map/JSON/String 进行互相转换
[4]. java对象转JSONObject
[5]. fastjson —JSONObject 和JSONArray 转换
[6]. Fastjson转换时,忽略某字段
[7]. 对象转json 方式方法与顺序问题

发表评论

表情:
评论列表 (有 0 条评论,32人围观)

还没有评论,来说两句吧...

相关阅读