使用GSON的JSON字符串到POJO,需要澄清

时间:2012-10-24 00:34:01

标签: java gson

我有一个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,好像从未设置过Component的名称值

我错过了什么?

2 个答案:

答案 0 :(得分: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 :(得分: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字符串中的内容然后成功了。