AdSense

網頁

2019/2/24

Java 物件轉JSON字串 - by Jaskson

把Java物件轉為json字串的方法如下。

可使用Jackson Databind函式庫來把Java物件轉為json字串,在Maven專案的pom.xml加入以下依賴。

<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.9.8</version>
</dependency>

或是用Gson函式庫也可達到一樣的效果,請參考Java 物件轉JSON字串 by Gson


使用ObjectMapper.writeValueAsString()轉Java物件為json字串的範例:

public class Main() {
    
    public static void main(String[] args) throws JsonProcessingException {
        
        User user = genUser(); // 取得Java物件
        
        ObjectMapper mapper = new ObjectMapper();
        String jsonString = mapper.writeValueAsString(user); // 轉成json字串
        System.out.println(jsonString);
        
        String prettyJsonString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(user); // 轉成整理過的json字串
        System.out.println(prettyJsonString);
    }

    private static User genUser() {
        Item item1 = new Item();
        item1.setId(101);
        item1.setName("筆記型電腦");
        item1.setQty(1);
        
        Item item2 = new Item();
        item2.setId(102);
        item2.setName("24吋LCD螢幕");
        item2.setQty(1);
        
        List<Item> itemList1 = new ArrayList<>();
        itemList1.add(item1);
        itemList1.add(item2);
        
        Order order1 = new Order();
        order1.setId(100001);
        order1.setItemList(itemList1);
        
        List<Order> orderList1 = new ArrayList<>();
        orderList1.add(order1);
        
        User user = new User();
        user.setId(1);
        user.setName("肉豬");
        user.setOrderList(orderList1);
        return user;
    }
    
}

class User {

    private Integer id;
    private String name;
    private List<Order> orderList;

    // 省略getter/setter
}

class Order {
    private Integer id;
    private List<Item> itemList;

    // 省略getter/setter
}

class Item {
    private Integer id;
    private Integer qty;
    private String name;

    // 省略getter/setter
}

印出以下結果

{"id":1,"name":"肉豬","orderList":[{"id":100001,"itemList":[{"id":101,"qty":1,"name":"筆記型電腦"},{"id":102,"qty":1,"name":"24吋LCD螢幕"}]}]}
{
  "id" : 1,
  "name" : "肉豬",
  "orderList" : [ {
    "id" : 100001,
    "itemList" : [ {
      "id" : 101,
      "qty" : 1,
      "name" : "筆記型電腦"
    }, {
      "id" : 102,
      "qty" : 1,
      "name" : "24吋LCD螢幕"
    } ]
  } ]
}

參考:

沒有留言:

AdSense