1. 程式人生 > >用java物件生成json資料

用java物件生成json資料

在微信開發中經常需要傳送json資料,這時候可以構建相應的物件以生成需要的json資料,舉例如下:

import com.fasterxml.jackson.databind.ObjectMapper;


/*
 * 將物件轉換為json資料
 * 
 * 以微信sdk生成帶引數的二維碼為例,生成如下json資料
 * {"expire_seconds": 604800, "action_name": "QR_SCENE", 
 * "action_info": {"scene": {"scene_id": 123}}}
 * 
 */

public class jsonTest {
    public
static void main(String[] args) throws Exception { //呼叫物件,增加資訊 Scene scene = new Scene(); scene.setScene_id("123"); Action_info action_info = new Action_info(); action_info.setScene(scene); JsonF jsonF = new JsonF(); jsonF.setExpire_seconds(604800
); jsonF.setAction_name("QR_SCENE"); jsonF.setAction_info(action_info); ObjectMapper mapper = new ObjectMapper(); String string = mapper.writeValueAsString(jsonF); System.out.println(string); } } /** * * 生成json資料的物件 */ class JsonF{ private int expire_seconds ; //有效期
private String action_name; //二維碼型別 private Action_info action_info; //場景資訊 public String getAction_name() { return action_name; } public void setAction_name(String action_name) { this.action_name = action_name; } public Action_info getAction_info() { return action_info; } public void setAction_info(Action_info action_info) { this.action_info = action_info; } public int getExpire_seconds() { return expire_seconds; } public void setExpire_seconds(int expire_seconds) { this.expire_seconds = expire_seconds; } } /** * 場景資訊類 * @author Lee * */ class Action_info{ private Scene scene; public Scene getScene() { return scene; } public void setScene(Scene scene) { this.scene = scene; } } /** * * @author Lee * */ class Scene{ private String scene_id; public String getScene_id() { return scene_id; } public void setScene_id(String scene_id) { this.scene_id = scene_id; } }

輸出結果:
eclipse控制檯
注:本例需要jackson-databind-2.8.2.jar報支援