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);

    }

結果:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM