簡體   English   中英

使用GSON將JSON字符串轉換為POJO,需要澄清

[英]JSON String to POJO, using GSON, clarification needed

我有一個JSON文件,如String

    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
}

我試圖通過以下方式將此String饋給此類:

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

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

以上不起作用。 (我得到的返回null ,好像從未設置組件的名稱值一樣)

我想念什么?

實際上,您必須從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";
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字符串中的某些內容,然后成功了。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM