2012-10-24 34 views
0

我有一個JSON文件,爲StringJSON字符串POJO,使用GSON,澄清需要

String compString = "{\n" + 
      "  \"Component\": {\n" + 
      "  \"name\": \"Application\",\n" + 
      "  \"environment\": \"QA\",\n" + 
      "  \"hosts\": [\n" + 
      "   \"box1\",\n" + 
      "   \"box2\"\n" + 
      "  ],\n" + 
      "  \"directories\": [\n" + 
      "   \"/path/to/dir1/\",\n" + 
      "   \"/path/to/dir2/\",\n" + 
      "   \"/path/to/dir1/subdir/\",\n" + 
      "  ]\n" + 
      "  }\n" + 
      " }"; 

我代表它的一個bean(正確的,如果不正確地)

public class Component { 

    String name; 
    String environment; 

    List<String> hosts = new ArrayList<String>(); 
    List<String> directories = new ArrayList<String>(); 

    // standard getters and setters 
} 

我想通過以下方式將此字符串提供給此類:

Gson gson = new Gson(); 
    Component component = gson.fromJson(compString, Component.class); 

    System.out.println(component.getName()); 

上述操作不起作用。 (我得到null回來,好像組件的名字值從未設置)

我在想什麼?

+0

您是否收到錯誤信息,或空豆? –

+0

在這一點上,我越來越'null'好像豆從未初始化 – JAM

回答

2

事實上,你必須從Json中刪除封閉的類。

的確,JSON從封閉類的內容開始。

所以,你的JSON是:

String compString = "{\n" + 
        "  \"name\": \"Application\",\n" + 
        "  \"environment\": \"QA\",\n" + 
        "  \"hosts\": [\n" + 
        "   \"box1\",\n" + 
        "   \"box2\"\n" + 
        "  ],\n" + 
        "  \"directories\": [\n" + 
        "   \"/path/to/dir1/\",\n" + 
        "   \"/path/to/dir2/\",\n" + 
        "   \"/path/to/dir1/subdir/\",\n" + 
        "  ]\n" + 
        "  }\n"; 
1
String compString = 
       "  {\n" + 
       "  \"name\": \"Application\",\n" + 
       "  \"environment\": \"QA\",\n" + 
       "  \"hosts\": [\n" + 
       "   \"box1\",\n" + 
       "   \"box2\"\n" + 
       "  ],\n" + 
       "  \"directories\": [\n" + 
       "   \"/path/to/dir1/\",\n" + 
       "   \"/path/to/dir2/\",\n" + 
       "   \"/path/to/dir1/subdir/\",\n" + 
       "  ]}" ; 

我想你應該閱讀更多關於json的信息,我已經刪除了json字符串中的某些內容,然後成功了。

+0

通過反覆試驗我得到了同樣的解決方案。謝謝 – JAM