2015-06-27 135 views
2

一個JSON對象,我已經寫在文件中的以下JSON,我想通過GSON閱讀:GSON解析與泛型類型

{ 
    "identifier": "CONFIG", 
    "data": [ 
    { 
     "identifier": "HOTKEY", 
     "data": { 
     "hotKey": "testKey1", 
     "type": "APPLICATION", 
     "runnableContext": "testContext1" 
     } 
    }, 
    { 
     "identifier": "HOTKEY", 
     "data": { 
     "hotKey": "testKey2", 
     "type": "APPLICATION", 
     "runnableContext": "testContext2" 
     } 
    } 
    ] 
} 

在上面的JSON,你可以看到標識&數據結構是遞歸地重複。所以,它表示此重複的圖案的基本類是如下所示的一般之一:

{ 
    "identifier": "CONFIG", 
    "data": { 

    } 
} 

此圖案由JsonData類表示如下:

import java.util.Set; 

.... 
import com.google.common.collect.ImmutableSet; 

/** 
* Class representing a simple {@link JsonData#identifier}, 
* {@link JsonData#data} format. This class can be used to 
* persist application data for example in a Configuration file. 
* 
* @author SW029693 
* @since v1.0 
*/ 
public class JsonData <T>{ 
    /** 
    * Represents a unique identifier 
    */ 
    private String identifier; 
    /** 
    * Represents the data pertaining to this {@link JsonData#identifier} 
    */ 
    private T data; 

    private static final Set<String> VALID_JSON_ID_TYPES = ImmutableSet.of("CONFIG","HOTKEYS","HOTKEY","RECOMMENDATIONS"); 

    public JsonData(String identifier, T data) { 
     super(); 
     this.identifier = identifier; 
     this.data = data; 
    } 

    /** 
    * Getter for {@link JsonData#identifier} 
    * @return 
    */ 
    public String getIdentifier() { 
     return identifier; 
    } 

    /** 
    * Sets the {@link JsonData#identifier} to the given value 
    * @param identifier 
    *   Represents a unique {@link JsonData#identifier} 
    * @throws VerifyException 
    *   If the argument is {@code null} or {@code empty} 
    */ 
    public void setIdentifier(String identifier) throws VerifyException{ 
     Verifier.verifyNotNull(identifier, "identifier : null"); 
     Verifier.verifyNotEmpty(identifier,"identifier : empty"); 
     this.identifier = identifier; 
    } 

    /** 
    * Getter for {@link JsonData} 
    * @return 
    */ 
    public T getData() { 
     return data; 
    } 

    /** 
    * Sets the {@link JsonData#data} to the given value 
    * @param identifier 
    *   Represents a unique {@link JsonData#data} 
    * @throws VerifyException 
    *   If the argument is {@code null} 
    */ 
    public void setData(T data) { 
     Verifier.verifyNotNull(data, "data : null"); 
     this.data = data; 
    } 

    @Override 
    public String toString() { 
     return "JsonData [identifier=" + identifier + ", data=" + data + "]"; 
    } 
} 

另外,在JSON以上,就可以看到每個熱鍵裏面的數據。這些數據將在通過gson閱讀json之後保存在ConfigurationProperty類中:

public class ConfigurationProperty implements Comparable<ConfigurationProperty>, Serializable{ 
....  
private final String hotKey; 
private final String type; 
private final String runnableContext; 
.... 

現在問題。我正在嘗試讀取該文件並解析Json,使用GSON將它存儲到各個對象中,但沒有運氣。

我有一些工作代碼讀取寫入到文件中的單個JsonData對象:

{ 
     "identifier": "HOTKEY", 
     "data": { 
     "hotKey": "testKey1", 
     "type": "APPLICATION", 
     "runnableContext": "testContext1" 
     } 
    } 

被成功地通過閱讀:

private static JsonData<ConfigurationProperty> readconfigFile() { 
    Reader reader = null; 
    JsonData<ConfigurationProperty> data = null; 
    Gson gson = null; 
    Type confType; 
    try { 
     reader = new FileReader("./config.json"); 
     gson = new GsonBuilder().create(); 
     confType = new TypeToken<JsonData<ConfigurationProperty>>() {}.getType(); 

     data = gson.fromJson(reader,confType); 
    } catch (FileNotFoundException e) { 
     e.printStackTrace(); 
     fail("Test failed while reading the config.json file: "+e.getMessage());  } 
    finally { 
     try { 
      reader.close(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
      fail("Test failed while reading the config.json file: "+e.getMessage()); 
     } 
    } 
    return data; 
} 

但是,如果你看一下第一個JSON,這是現在是JsonData的遞歸結構。同樣在解析時,我需要告訴Gson第一個數據對象是JsonData對象的ARRAY。我還需要告訴gson該數組中的每個JSONData對象都是類型ConfigurationProperty。

我不知道如何做到這一點。

回答

1

我想通了。這是我怎麼做的

private static JsonData<List<ConfigurationProperty>> readconfigFileList() { 
    Reader reader = null; 
    JsonData<List<ConfigurationProperty>> dataArray = null; 
    Gson gson = null; 
    Type confType; 
    Type confTypeArray; 
    try { 
     reader = new FileReader("./config.json"); 
     gson = new GsonBuilder().create(); 
     confType = new TypeToken<JsonData<List<ConfigurationProperty>>>() {}.getType(); 

     dataArray = gson.fromJson(reader,confType); 
     System.out.println(dataArray.toString()); 

    } catch (FileNotFoundException e) { 
     e.printStackTrace(); 
     fail("Test failed while reading the config.json file: "+e.getMessage());  } 
    finally { 
     try { 
      reader.close(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
      fail("Test failed while reading the config.json file: "+e.getMessage()); 
     } 
    } 
    return dataArray; 
} 
1

找到下面的代碼爲通用Json對象分析或未知的Json對象分析使用Gson庫。

public class JsonParsing { 

    static JsonParser parser = new JsonParser(); 

    public static HashMap<String, Object> createHashMapFromJsonString(String json) { 

     JsonObject object = (JsonObject) parser.parse(json); 
     Set<Map.Entry<String, JsonElement>> set = object.entrySet(); 
     Iterator<Map.Entry<String, JsonElement>> iterator = set.iterator(); 
     HashMap<String, Object> map = new HashMap<String, Object>(); 

     while (iterator.hasNext()) { 

      Map.Entry<String, JsonElement> entry = iterator.next(); 
      String key = entry.getKey(); 
      JsonElement value = entry.getValue(); 

      if (null != value) { 
       if (!value.isJsonPrimitive()) { 
        if (value.isJsonObject()) { 

         map.put(key, createHashMapFromJsonString(value.toString())); 
        } else if (value.isJsonArray() && value.toString().contains(":")) { 

         List<HashMap<String, Object>> list = new ArrayList<>(); 
         JsonArray array = value.getAsJsonArray(); 
         if (null != array) { 
          for (JsonElement element : array) { 
           list.add(createHashMapFromJsonString(element.toString())); 
          } 
          map.put(key, list); 
         } 
        } else if (value.isJsonArray() && !value.toString().contains(":")) { 
         map.put(key, value.getAsJsonArray()); 
        } 
       } else { 
        map.put(key, value.getAsString()); 
       } 
      } 
     } 
     return map; 
    } 
} 

〜錢德拉