Java中Json与String互转

1、引入依赖(如果非maven管理,也可手动下载相关jar包)

    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>fastjson</artifactId>
      <version>1.2.58</version>
    </dependency>

2、示例代码

public class App 
{
    public static void main( String[] args )
    {
        User user1 = new User("小明","123");
        User user2 = new User("小李","123");
        //1、List 转 Json
        List<User>list = new ArrayList<>();
        list.add(user1);
        list.add(user2);
        String listToString = JSON.toJSONString(list);
        System.out.println("--------List转Json--------");
        System.out.println(listToString);
        //4、Json转List
        List<User> jsonToList = JSONArray.parseArray(listToString, User.class);
        System.out.println("--------Json转List--------");
        for(int i = 0; i < jsonToList.size(); i++){
            System.out.println(jsonToList.get(i));
        }
    }
}
posted @ 2020-01-04 16:13  小楼夜听雨QAQ  阅读(6209)  评论(0编辑  收藏  举报