fastJson中常用JSON字符串和Java对象互转

Posted 天之骄子zz

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了fastJson中常用JSON字符串和Java对象互转相关的知识,希望对你有一定的参考价值。

1.使用fastJson,首先引入fastJson依赖

<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.54</version>
</dependency>

2.JSON String to Java Bean

/**
 * JSON->Java Bean
 */
@Test
public void test1(){
    Person person = new Person().setId("1").setName("fastJson").setAge(1);
    String jsonString = JSON.toJSONString(person);
    System.out.println(jsonString);
//传入字节码,调用parseObject Person person1
= JSON.parseObject(jsonString, Person.class); System.out.println(person1); }

3.JSON String to List Java Bean

/**
 * JSON->List Java Bean
 */
@Test
public void test2(){
    List<Person> list = Arrays.asList(new Person().setId("1").setName("fastJson1").setAge(1),
            new Person().setId("2").setName("fastJson2").setAge(2),
            new Person().setId("3").setName("fastJson3").setAge(3));
    String jsonString = JSON.toJSONString(list);
    System.out.println(jsonString);
//传入字节码,调用parseArray List
<Person> person1 = JSON.parseArray(jsonString, Person.class); System.out.println(person1); }

4.JSON String to List String

/**
 * JSON->List String
 */
@Test
public void test3(){
    List<String> list = Arrays.asList("hello","world","hello world");
    String jsonString = JSON.toJSONString(list);
    System.out.println(jsonString);
   // new TypeReference<List<String>>() {} List
<String> list1 = JSON.parseObject(jsonString, new TypeReference<List<String>>() {}); System.out.println(list1); }

5.JSON String to List<Map<String,Object>>

/**
 * JSON->List<Map<String,Object>>
 */
@Test
public void test4(){
    List<Map<String,Object>> list = new ArrayList<>();
    Map<String,Object> map = new HashMap<>();
    map.put("key1","value1");
    map.put("key2","value2");
    list.add(map);
    Map<String,Object> map1 = new HashMap<>();
    map1.put("key11","value11");
    map1.put("key22","value22");
    list.add(map1);
    Map<String,Object> map2 = new HashMap<>();
    map2.put("key111","value111");
    map2.put("key222","value222");
    list.add(map2);
    String jsonString = JSON.toJSONString(list);
    System.out.println(jsonString);
  // new TypeReference<T> List
<Map<String, Object>> maps = JSON.parseObject(jsonString, new TypeReference<List<Map<String, Object>>>() {}); System.out.println(maps); }

 





以上是关于fastJson中常用JSON字符串和Java对象互转的主要内容,如果未能解决你的问题,请参考以下文章

JAVA 中 提取 alibaba.fastjson.JSONObject 字符串中的 KEY 和 VALUE 值

Fastjson 之 Json 对象Json 字符串Java 对象之间的转换

fastjson使用详解

FastJson:json字符串与Java对象转换

java FastJson的使用

JSON_常用类JSON与对象的互相转换TypeReference泛型遇到的坑