2013-03-16 203 views
2

我想解析一個json字符串到java對象。目前代碼是手動讀取文件並生成java對象。但是,我期待着實施gson。gson解析嵌套的json對象

這裏是我從Web服務調用收到JSON:

{ "comment": [ 
     "This file is used to define the behavior for the elements parsed.", 
     "Each entry in the file will have the format of element:name, skip:bool", 
     "If SkipFlag is true, it means that element need not be processed.", 
     "Convention used for elements and rule names is camelCase" 
    ], 
    "rules": [ { "element": "html", "skip": true }, 
       { "element": "head", "skip": true }, 
       { "element": "head", "skip": true }, 
       { "element": "body", "skip": true } 
    ] 
} 

我需要忽略的意見和轉換規則。這裏是我試圖定義規則,Java對象的Java類型:

// Arraylist < Map < elementname, Map < name, value > > > 
ArrayList< Map<String, Map<String, String> > > rules; 

是否與GSON這樣做的一個簡單的方法?

回答

3

您可以聲明特定類:

import java.io.BufferedReader; 
import java.io.FileReader; 
import java.io.IOException; 

import com.google.gson.Gson; 

class Rule { 
    String element; 
    boolean skip; 
} 

class ElementParser { 
    String[] comment; 
    Rule[] rules; 
} 

public class JSonDecoder { 
    public static void main(String[] args) throws IOException { 
     try(BufferedReader reader = 
       new BufferedReader(new FileReader("Skip.json"))) { 
     System.out.println( 
      new Gson().fromJson(reader, ElementParser.class).toString()); 
     } 
    } 
} 

這裏是版本:

import java.io.BufferedReader; 
import java.io.FileReader; 
import java.io.IOException; 

import com.google.gson.Gson; 

class Rule { 
    String element; 
    boolean skip; 

    @Override public String toString() { 
     StringBuilder sb = new StringBuilder(); 
     sb.append('\t'); 
     sb.append(element); 
     sb.append(" ==> "); 
     sb.append(skip); 
     sb.append('\n'); 
     return sb.toString(); 
    } 
} 
class ElementParser { 
    String[] comment; 
    Rule[] rules; 

    @Override public String toString() { 
     StringBuilder sb = new StringBuilder(); 
     sb.append("Comment:\n"); 
     for(String c : comment) { 
     sb.append('\t'); 
     sb.append(c); 
     sb.append('\n'); 
     } 
     sb.append("Rules:\n"); 
     for(Rule r : rules) { 
     sb.append(r.toString()); 
     } 
     return sb.toString(); 
    } 
} 

public class JSonDecoder { 
    public static void main(String[] args) throws IOException { 
     try(BufferedReader reader = new BufferedReader(new FileReader("Skip.json"))) { 
     System.out.println( 
      new Gson().fromJson(reader, ElementParser.class).toString()); 
     } 
    } 
} 

結果:

Comment: 
    This file is used to define the behavior for the elements parsed. 
    Each entry in the file will have the format of element:name, skip:bool 
    If SkipFlag is true, it means that element need not be processed. 
    Convention used for elements and rule names is camelCase 
Rules: 
    html ==> true 
    head ==> true 
    head ==> true 
    body ==> true 
+1

規則是'每個文件只有一個**公共類**'。 http://docs.oracle.com/javase/specs/jls/se7/html/jls-7.html#jls-7.6 – Aubin 2013-03-16 17:54:48

5

使用此

GsonBuilder builder = new GsonBuilder();  
Gson gson = builder.enableComplexMapKeySerialization().create(); 
Type type = new TypeToken<ArrayList< Map<String, ArrayList<Map<String, String> > > >>() {}.getType(); 
ArrayList< Map<String, ArrayList<Map<String, String> > > > obj = gson.fromJson(str, type); 
+0

你能解釋一下嗎? 'gson.fromJson'中的類型規範是否自動從json中查找匹配類型?我想了解'comment'對象是如何被跳過的。 – Kiran 2013-03-16 17:22:02

+0

類型規範(新的TypeToken等)可以協助Gson序列化複雜類型(即當對象派生出密鑰時,即使你的地圖使用普通字符串時,對象列表甚至地圖)。我想你可以創建一個適合你的JSON字符串的自定義類型,將其序列化(包括註釋!),並簡單地忽略它們。 – 2013-03-16 17:28:17

2

你可以試試這個太..

數據類的牽着你的規則和評論

import java.util.List; 

public class Data { 

    private List<String> comments; 
    private List<Rule> rules; 

    public Data() {} 

    public List<String> getComments() { 
     return comments; 
    } 

    public void setComments(List<String> comments) { 
     this.comments = comments; 
    } 

    public List<Rule> getRules() { 
     return rules; 
    } 

    public void setRules(List<Rule> rules) { 
     this.rules = rules; 
    } 

} 

規則類的保持元件,並跳過 公共類規則{

private String element; 
    private boolean skip; 

    public Rule() {} 

    public String getElement() { 
     return element; 
    } 

    public void setElement(String element) { 
     this.element = element; 
    } 

    public boolean isSkip() { 
     return skip; 
    } 

    public void setSkip(boolean skip) { 
     this.skip = skip; 
    } 

} 

最後,你可以使用這樣的東西來將你的json中的規則轉換爲java:

import java.io.BufferedReader; 
import java.io.FileNotFoundException; 
import java.io.FileReader; 
import java.util.List; 

import com.google.gson.Gson; 

public class GsonTest { 

    public static void main(String[] args) throws FileNotFoundException { 
     BufferedReader bufferedReader = new BufferedReader(new FileReader("C:/Users/JESNAMOL/Desktop/json.txt"));//i have kept your json string in a file for demonstration 
     Gson gson = new Gson(); 
     Data data = gson.fromJson(bufferedReader, Data.class); 
     List<Rule> rules = data.getRules(); 

     for (Rule rule : rules) { 
      System.out.println("element: " + rule.getElement()); 
      System.out.println("skip: " + rule.isSkip()); 
     } 
    } 

} 
+0

不能像這樣工作。規則將變爲空白。 – Diffy 2014-12-04 07:16:08