2017/6/9

Java解析Json常用程式碼

如果我有個需求要提取出以下Json中的NAME,並再把它做成可以給某個系統吃的Json格式。

[
   {
      "flag":0,
      "DESCRIPTION":"創立於1980年,創始人從小精心學習製作當地傳統食品,從基隆惠隆市場白手起家;第二代老闆秉持製作過程的堅持,將麻花加入基隆的海苔,濃郁的香氣,香甜酥脆的口感,兼顧了在地和健康的特色,因此獲得基隆十大伴手禮。",
      "ADDRESS":"基隆市仁愛區仁二路77號",
      "OPENTIME":"08:00~22:00",
      "PX":"121.749100",
      "PY":"25.127610",
      "TEL":"886-2-24233584",
      "ID":1663,
      "CLASS":"伴手禮",
      "WEBSITE":"http://www.kofuu.com/",
      "NAME":"口福食品行"
   },
   {
      "flag":0,
      "DESCRIPTION":"產品有伴手禮系列、大餅系列、喜餅系列等;「咖哩魯肉餅」獲基隆十大伴手禮,以獨特配方,採兩面烘焙法,外酥內軟,香氣四溢、不油不膩。另外,「綠豆魯肉餅」以草本植物和綠豆為內餡,香氣四溢,也十分受歡迎。",
      "ADDRESS":"基隆市暖暖區源遠路249巷179之1號",
      "OPENTIME":"08:30~20:30(週一公休)",
      "PX":"121.753900",
      "PY":"25.099980",
      "TEL":"886-2-24592368",
      "ID":1664,
      "CLASS":"伴手禮",
      "WEBSITE":"http://www.cakefamily.com.tw/",
      "NAME":"大餅世家"
   }
   ...
]
通常這樣的資料集會有很多筆,總不能一比一比慢慢打吧?!

給某個系統吃的Json格式假設是這樣:
{
  "id": "c3cbe231-5b8d-49d5-bdf6-68ffba3565db",
  "name": "shop",
  "isOverridable": true,
  "entries": [
    {
      "value": "切仔麵",
      "synonyms": [
        "切仔麵"
      ]
    },
    {
      "value": "香米湯湯",
      "synonyms": [
        "香米湯湯",
        "湯湯"
      ]
    },
    {
      "value": "祥豐陽光早餐吧",
      "synonyms": [
        "祥豐陽光早餐吧",
        "陽光早餐"
      ]
    }
    ...
   ],
  "isEnum": false,
  "automatedExpansion": true
}
第一步:先做出第一段Json的Java物件程式碼
可以利用這個網站產生 http://www.jsonschema2pojo.org/
我是有用Gson和Apache Commons Lang 3.5
產生程式碼的如下:
package pojo;

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import org.apache.commons.lang3.builder.ToStringBuilder;

public class Principal {

    @SerializedName("flag")
    @Expose
    private Integer flag;
    @SerializedName("DESCRIPTION")
    @Expose
    private String dESCRIPTION;
    @SerializedName("ADDRESS")
    @Expose
    private String aDDRESS;
    @SerializedName("OPENTIME")
    @Expose
    private String oPENTIME;
    @SerializedName("PX")
    @Expose
    private String pX;
    @SerializedName("PY")
    @Expose
    private String pY;
    @SerializedName("TEL")
    @Expose
    private String tEL;
    @SerializedName("ID")
    @Expose
    private Integer iD;
    @SerializedName("CLASS")
    @Expose
    private String cLASS;
    @SerializedName("WEBSITE")
    @Expose
    private String wEBSITE;
    @SerializedName("NAME")
    @Expose
    private String nAME;

    public Integer getFlag() {
        return flag;
    }

    public void setFlag(Integer flag) {
        this.flag = flag;
    }

    public String getDESCRIPTION() {
        return dESCRIPTION;
    }

    public void setDESCRIPTION(String dESCRIPTION) {
        this.dESCRIPTION = dESCRIPTION;
    }

    public String getADDRESS() {
        return aDDRESS;
    }

    public void setADDRESS(String aDDRESS) {
        this.aDDRESS = aDDRESS;
    }

    public String getOPENTIME() {
        return oPENTIME;
    }

    public void setOPENTIME(String oPENTIME) {
        this.oPENTIME = oPENTIME;
    }

    public String getPX() {
        return pX;
    }

    public void setPX(String pX) {
        this.pX = pX;
    }

    public String getPY() {
        return pY;
    }

    public void setPY(String pY) {
        this.pY = pY;
    }

    public String getTEL() {
        return tEL;
    }

    public void setTEL(String tEL) {
        this.tEL = tEL;
    }

    public Integer getID() {
        return iD;
    }

    public void setID(Integer iD) {
        this.iD = iD;
    }

    public String getCLASS() {
        return cLASS;
    }

    public void setCLASS(String cLASS) {
        this.cLASS = cLASS;
    }

    public String getWEBSITE() {
        return wEBSITE;
    }

    public void setWEBSITE(String wEBSITE) {
        this.wEBSITE = wEBSITE;
    }

    public String getNAME() {
        return nAME;
    }

    public void setNAME(String nAME) {
        this.nAME = nAME;
    }

    @Override
    public String toString() {
        return ToStringBuilder.reflectionToString(this);
    }

}


接下來就可以開始寫程式了

程式碼如下:
package parsekeelungshopjson;

import com.google.gson.Gson;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import pojo.Principal;

public class ParseKeelungShopJson {
    public static void main(String[] args) throws IOException {
        Gson gson = new Gson();
        String jsonFilePath = "/Users/xanxus/Downloads/基隆商家資料.txt";
        String content = new String(Files.readAllBytes(Paths.get(jsonFilePath)));
        Principal[] enums = gson.fromJson(content, Principal[].class);
        for(Principal b : enums){
            System.out.println("{\"value\": \""+b.getNAME()+"\", \"synonyms\": [\""+b.getNAME()+"\"] },");
        }
    }
}
輸出結果:
{"value": "口福食品行", "synonyms": ["口福食品行"] },
{"value": "大餅世家", "synonyms": ["大餅世家"] },
{"value": "北都冷凍食品", "synonyms": ["北都冷凍食品"] },
{"value": "基隆市永康社區發展協會(阿母ㄟ灶腳)", "synonyms": ["基隆市永康社區發展協會(阿母ㄟ灶腳)"] },
...

另一個例子,現在我有以下的json,最好先把最外面那層大括號拿掉,否則可以會錯誤
[
    [
        {
            "distance":"24 公尺",
            "duration":"1 分",
            "end_location":{
                "X":121.7398062,
                "Y":25.1319319
            },
            "start_location":{
                "X":121.7396032,
                "Y":25.132037
            },
            "html_instructions":"往東南走港西街",
            "polyline":"grkxCog`fV@A@?FIBIDS",
            "travel_mode":"WALKING"
        },
        {
            "distance":"0.2 公里",
            "duration":"3 分",
            "end_location":{
                "X":121.73853,
                "Y":25.1309674
            },
            "start_location":{
                "X":121.7398062,
                "Y":25.1319319
            },
            "html_instructions":"使用行人天橋走樓梯",
            "polyline":"qqkxCyh`fV\\FFDLHFFPR?J?R?Z@X?R?D@D@DBFBB@Bf@Xx@d@",
            "travel_mode":"WALKING"
        }
        ..............
    ]
]
一樣把它拿去餵 http://www.jsonschema2pojo.org/ 也就是先做好這個json的class物件 然後就可以開始寫程式了,如下
package parsekeelungshopjson;

import com.google.gson.Gson;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import pojo.shopdata.Principal;
public class ParseKeelungShopJson {
    public static void main(String[] args) throws IOException {
        Gson gson = new Gson();
        String jsonFilePath = "/Users/xanxus/Downloads/Sublime程式碼備份/基隆火車站到屏東火車站_GoogleMapJson資料.json";
        String content = new String(Files.readAllBytes(Paths.get(jsonFilePath)));
        pojo.googlemaprouteinstruction.Principal[] enums = gson.fromJson(content, pojo.googlemaprouteinstruction.Principal[].class);
        int a = 1;
        for(pojo.googlemaprouteinstruction.Principal b : enums){
            System.out.println(a+++b.getHtmlInstructions());
        }
    }
}
出來的結果:
1往東南走港西街
2使用行人天橋走樓梯
3於中山陸橋/忠二路向右轉繼續開在中山陸橋上
4接著走安一路
5於樂一路向左轉
6於樂一路28巷向右轉
.....


再來我有以下資料:
往東南走港西街
使用行人天橋走樓梯
於中山陸橋/忠二路向右轉繼續開在中山陸橋上
接著走安一路
於樂一路向左轉
於樂一路28巷向右轉
向左轉,朝崇德路10巷前進
向右轉,朝崇德路10巷前進
...
我們需要把他們做成Json 先創造一個這個資料的物件類別:
package txttojson;
public class BagOfPrimitives {
    private String htmlInstructions;

    public String getHtmlInstructions() {
        return htmlInstructions;
    }

    public void setHtmlInstructions(String htmlInstructions) {
        this.htmlInstructions = htmlInstructions;
    }

    @Override
    public String toString() {
        return "BagOfPrimitives{" + "htmlInstructions=" + htmlInstructions + '}';
    }

}
最後程式碼這麼寫:
package parsekeelungshopjson;

import com.google.gson.Gson;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import pojo.shopdata.Principal;
import txttojson.BagOfPrimitives;
public class ParseKeelungShopJson {
    public static void main(String[] args) throws IOException {

        Gson gson = new Gson();

        String jsonFilePath = "/Users/xanxus/Downloads/Sublime程式碼備份/基隆火車站到屏東火車站_GoogleMap路線指示資料";
        String content = new String(Files.readAllBytes(Paths.get(jsonFilePath)));

        String[] instructions = content.split("\n");

        BagOfPrimitives[] bop = new BagOfPrimitives[instructions.length];
        for(int i = 0 ; i<instructions.length ; i++){
            bop[i] = new BagOfPrimitives();
            bop[i].setHtmlInstructions(instructions[i]);
        }

        String htmlInstructionsJson = gson.toJson(bop);
        System.out.println(htmlInstructionsJson);
    }
}


Gson gson = new GsonBuilder().disableHtmlEscaping().setFieldNamingPolicy(FieldNamingPolicy.IDENTITY).create();//將特殊字元正常輸出不轉換
參考資料:http://bit.ly/2slZlPB ★★★

沒有留言:

張貼留言