使用fastjson实现Json与对象、List的转换

为了测试,先建一个类Article.java

@Data #这里用的lombok
@AllArgsConstructor
@NoArgsConstructor
public class Article {

    private Integer id;

    private String summary;

    private String author;
}

然后测试类

public void outSay(){
        Article article = new Article(1,"我没说过","鲁迅");
        Article article1 = new Article(2,"我说过了","周树人");

        List<Article> list=new ArrayList<>();
        list.add(article);
        list.add(article1);

        //对象转为Json字符串
        String a= JSON.toJSONString(article);
        String a1= JSON.toJSONString(article1);
        System.out.println(a);
        System.out.println(a1);

        JSONObject jsonObject=JSONObject.parseObject(a);

        //Json转对象
        Object id=jsonObject.get("id");
        System.out.println(id.getClass()+" : "+id);

        Object summary=jsonObject.get("summary");
        System.out.println(summary.getClass()+" : "+summary);

        //List转json
        Object listToJson = JSON.toJSON(list);
        System.out.println(listToJson);


        //json转List
        String listToJson1=JSON.toJSONString(listToJson);
        List<Article> articleList= JSONArray.parseArray(listToJson1,Article.class);
        articleList.forEach(obj->System.out.println(obj.toString()));
    }

输出结果

{"author":"鲁迅","id":1,"summary":"我没说过"}
{"author":"周树人","id":2,"summary":"我说过了"}
class java.lang.Integer : 1
class java.lang.String : 我没说过
[{"summary":"我没说过","author":"鲁迅","id":1},{"summary":"我说过了","author":"周树人","id":2}]
Article(id=1, summary=我没说过, author=鲁迅)
Article(id=2, summary=我说过了, author=周树人)
©️2020 CSDN 皮肤主题: 深蓝海洋 设计师:CSDN官方博客 返回首页