Java 实现 对象和转字符串之间的互转 (json格式)

 

添加依赖:

  <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.9.7</version>
  </dependency>

  <dependency>
            <groupId>com.squareup.retrofit2</groupId>
            <artifactId>converter-gson</artifactId>
            <version>2.5.0</version>
  </dependency>

 

 

 

 

下面直接上代码:

 

 

实体类:  注意实体类想要序列化一定要实现 Serializable 接口 否则不能通过

package com.nf147.sim.entity;

import java.io.Serializable;

public class News implements Serializable {
    private int id;
    private String title;
    private String body;

    public News() {
    }

    public News(int id, String title, String body) {
        this.id = id;
        this.title = title;
        this.body = body;
    }

    public News(String title, String body) {
        this.title = title;
        this.body = body;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getBody() {
        return body;
    }

    public void setBody(String body) {
        this.body = body;
    }

    @Override
    public String toString() {
        return "News{" +
                "id=" + id +
                ", title='" + title + '\'' +
                ", body='" + body + '\'' +
                '}';
    }
}

 

 

 

 

 

public void toJosn() throws Exception {
        ObjectMapper objectMapper = new ObjectMapper(); //json

        // java 对象 -> json 字符串
        // json 字符串 -> java 对象

        News news = new News("kudankuaidaole", "放假通知");
        String s = objectMapper.writeValueAsString(news);

        System.out.println("对象转字符串:"+s);
        System.out.println("=============");

        List<News> newsList = Arrays.asList(
                new News("yuandan", "放假"),
                new News("春节", "快来了")
        );

        //第一种方式
        String newslistStr = objectMapper.writeValueAsString(newsList);
        News[] newsArray = objectMapper.readValue(newslistStr, News[].class);
        List<News> newsList1 = objectMapper.readValue(newslistStr, new TypeReference<List<News>>() {
        });

        System.out.println();
        System.out.println("字符串转对象:"+newsList1);

        //第二种方式
        List<News> newsList2 = new Gson().fromJson(newslistStr, new TypeToken<List<News>>() {}.getType()); //使用gson
        System.out.println("字符串转对象:"+newsList2);

    }

结果:

 

posted @ 2018-12-27 20:48  随★风  阅读(9166)  评论(0编辑  收藏  举报