2017/4/16

好用的Json to POJO工具

之前做Json的POJO都笨笨的自己慢慢打慢慢刻,後來才發現其實有線上工具可以幫我們自動產生。
就是這個網站:http://www.jsonschema2pojo.org/


首先我有一個Json格式是這樣:
{
    "id":"2993688d-4122-4c33-813c-2ddd10268c93",
    "timestamp":"2017-04-15T13:54:37.254Z",
    "lang":"en",
    "result":{
        "source":"agent",
        "resolvedQuery":"我要去台北",
        "action":"TheAction",
        "actionIncomplete":false,
        "parameters":{
            "taiwan-city":[
                "台北"
            ]
        },
        "contexts":[

        ],
        "metadata":{
            "intentId":"58e62519-f775-4a66-8655-ac772d157cec",
            "webhookUsed":"false",
            "webhookForSlotFillingUsed":"false",
            "intentName":"TheIntent"
        },
        "fulfillment":{
            "speech":"請稍等,正在幫你處理。",
            "messages":[
                {
                    "type":0,
                    "speech":"請稍等,正在幫你處理。"
                }
            ]
        },
        "score":1.0
    },
    "status":{
        "code":200,
        "errorType":"success"
    },
    "sessionId":"1234567890"
}
看得出來這段要變成POJO有點不容易,只有對結構很熟悉的人能手刻出來,像我不熟悉就可以利用這個網站來轉換。

開啟那個網站把Json貼上去
Source type我選JSON,不知為啥選JSON Schema產出的ZIP打不開
因為我是用Gson解析,所以選Gson,其他都預設。
試過勾Include toString,但它產出的很像是用Apache Commons Lang來做,而我引入了Apache Commons Lang函式庫還是不能用,因此沒勾。

2017-5-3補充:
因它產出的Apache Commons Lang似乎是初版的,程式碼是這樣:
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import org.apache.commons.lang.builder.ToStringBuilder;
...
因我當時是下載Apache Commons Lang 3.5那當然不能用了,只要加個3上去就可以了!像這樣:
...
org.apache.commons.lang3.builder.ToStringBuilder;
...

選好點下面的Zip,就自動幫你產出了!
左邊的Preview就是預覽。

解壓縮ZIP,把產出的Java檔放進Java Application專案中。

來使用吧:
package apiai;
import pojo.*;
import com.google.gson.FieldNamingPolicy;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import static org.apache.http.HttpHeaders.USER_AGENT;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

public class HttpClientExample {

    public static void main(String[] args) throws Exception {
        HttpClientExample http = new HttpClientExample();

        System.out.println("Testing 1 - Send Http GET request");
        http.sendGet();
    }

    private void sendGet() throws Exception {

        String url = "https://api.api.ai/v1/query?v=20150910&query=我要去台北&lang=en&sessionId=1234567890";

        HttpClient client = new DefaultHttpClient();
        HttpGet request = new HttpGet(url);

        // add request header
        request.addHeader("User-Agent", USER_AGENT);
        request.addHeader("Authorization", "Bearer f67256b80e344e86affdd20487734835" );
        HttpResponse response = client.execute(request);

        System.out.println("\nSending 'GET' request to URL : " + url);
        System.out.println("Response Code : " + response.getStatusLine().getStatusCode());

        BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
        String SerializationResult = "";
        StringBuffer result = new StringBuffer();
        String line = "";
        while ((line = rd.readLine()) != null) {
            result.append(line);
            SerializationResult = result.toString();
        }
        Gson gson = new GsonBuilder().disableHtmlEscaping().setFieldNamingPolicy(FieldNamingPolicy.IDENTITY).create();//將特殊字元正常輸出不轉換

        Principal r = gson.fromJson(SerializationResult, Principal.class);

        System.out.println(r.getResult());

    }
}

重點是46~50行 輸出結果:
Testing 1 - Send Http GET request

Sending 'GET' request to URL : https://api.api.ai/v1/query?v=20150910&query=我要去台北&lang=en&sessionId=1234567890
Response Code : 200
Result{source=agent, resolvedQuery=我要去台北, action=TheAction, actionIncomplete=false, parameters=Parameters{taiwanCity=[台北]}, contexts=[], metadata=Metadata{intentId=58e62519-f775-4a66-8655-ac772d157cec, webhookUsed=false, webhookForSlotFillingUsed=false, intentName=TheIntent}, fulfillment=Fulfillment{speech=請稍等,正在幫你處理。, messages=[Message{type=0, speech=請稍等,正在幫你處理。}]}, score=1.0}
可以看得出非常成功,另外POJO的toString是我用IDE產出的,原因上面有說明,因為那網站產出的我還不會用

抓Result下一層資料的寫法:
Gson gson = new GsonBuilder().disableHtmlEscaping().setFieldNamingPolicy(FieldNamingPolicy.IDENTITY).create();//將特殊字元正常輸出不轉換
Principal r = gson.fromJson(SerializationResult, Principal.class);
System.out.println(r.getResult().getResolvedQuery());
就只是後面再加個get而已

如果要抓那個最底層的type 0呢?
Gson gson = new GsonBuilder().disableHtmlEscaping().setFieldNamingPolicy(FieldNamingPolicy.IDENTITY).create();//將特殊字元正常輸出不轉換
Principal r = gson.fromJson(SerializationResult, Principal.class);
System.out.println(r.getResult().getFulfillment().getMessages().get(0).getType());
恩比較特別,讓我稍微試了幾次
輸出:
Testing 1 - Send Http GET request

Sending 'GET' request to URL : https://api.api.ai/v1/query?v=20150910&query=我要去台北&lang=en&sessionId=1234567890
Response Code : 200
0



附上Principal類別以作參考:
package pojo;

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class Principal {

    @SerializedName("id")
    @Expose
    private String id;
    @SerializedName("timestamp")
    @Expose
    private String timestamp;
    @SerializedName("lang")
    @Expose
    private String lang;
    @SerializedName("result")
    @Expose
    private Result result;
    @SerializedName("status")
    @Expose
    private Status status;
    @SerializedName("sessionId")
    @Expose
    private String sessionId;

    public String getId() {
        return id;
    }

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

    public String getTimestamp() {
        return timestamp;
    }

    public void setTimestamp(String timestamp) {
        this.timestamp = timestamp;
    }

    public String getLang() {
        return lang;
    }

    public void setLang(String lang) {
        this.lang = lang;
    }

    public Result getResult() {
        return result;
    }

    public void setResult(Result result) {
        this.result = result;
    }

    public Status getStatus() {
        return status;
    }

    public void setStatus(Status status) {
        this.status = status;
    }

    public String getSessionId() {
        return sessionId;
    }

    public void setSessionId(String sessionId) {
        this.sessionId = sessionId;
    }

    @Override
    public String toString() {
        return "Principal{" + "id=" + id + ", timestamp=" + timestamp + ", lang=" + lang + ", result=" + result + ", status=" + status + ", sessionId=" + sessionId + '}';
    }

}

沒有留言:

張貼留言