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

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



    com.alibaba
    fastjson
    1.2.54

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 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
person1 = JSON.parseArray(jsonString, Person.class); System.out.println(person1); }

4.JSON String to List String

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

5.JSON String to List>

/**
 * JSON->List>
 */
@Test
public void test4(){
    List> list = new ArrayList<>();
    Map map = new HashMap<>();
    map.put("key1","value1");
    map.put("key2","value2");
    list.add(map);
    Map map1 = new HashMap<>();
    map1.put("key11","value11");
    map1.put("key22","value22");
    list.add(map1);
    Map 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 List
> maps = JSON.parseObject(jsonString, new TypeReference>>() {}); System.out.println(maps); }

 

转载于:https://www.cnblogs.com/ixan/p/10166408.html

你可能感兴趣的:(fastJson中常用JSON字符串和Java对象互转)