0

我有一个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
}

我正在尝试通过以下方式将此字符串提供给此类:

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

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

以上不起作用。(我null回来了,好像从未设置过组件的名称值)

请问我错过了什么?

4

2 回答 2

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";
于 2012-10-24T00:55:31.443 回答
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 字符串中的某些内容,然后成功了。

于 2012-10-24T00:54:23.027 回答