我使用C#
编写的Web服务执行一些基本的数据库访问,并返回带有该信息的JSON
字符串。我需要将其转换为名为Role
的对象数组(每个Role
代表数据库中的一行 - RoleId
和ShortDesc
)。
在Web服务中,使用Jackson JSON库生成JSON,如下所示:
String output = JsonConvert.SerializeObject(DataTable);
这给了我以下输出:
getJsonTableResponse
{getJsonTableResult=[
{"RoleId":"1de15a5f-0219-4ad9-a5eb-b214238d9cfd","ShortDesc":"description"},
{"RoleId":"f60d8403-9c3c-493b-844c-7ac8ff001b2b","ShortDesc":"description"},
{"RoleId":"b65eecd7-d551-4706-af7a-51d8e4d5093f","ShortDesc":"description"},
{"RoleId":"fbcea65a-5b75-409c-b722-3cb4306c8471","ShortDesc":"description"},
{"RoleId":"fdbc73b2-9fbb-4f3a-a087-3ec41a6800f9","ShortDesc":"description"},
{"RoleId":"360ae291-f8dd-430d-bb1f-ff04bada68c7","ShortDesc":"description"},
{"RoleId":"e363780b-26ae-4580-8b13-22d24fd098d8","ShortDesc":"description"},
{"RoleId":"4b3d37a4-4c8d-42f5-9378-52b0ab6ede30","ShortDesc":"description"}];
}
使用java
,如何将此JSON
字符串转换为Role
个对象的数组(由RoleId
和ShortDesc
字符串字段组成)?我是JSON
的新手,到目前为止一直在努力对其进行反序列化。
答案 0 :(得分:1)
首先,我猜你的json字符串应该是这样的:
{
"getJsonTableResult": [
{
"RoleId": "1de15a5f-0219-4ad9-a5eb-b214238d9cfd",
"ShortDesc": "description"
},
{
"RoleId": "f60d8403-9c3c-493b-844c-7ac8ff001b2b",
"ShortDesc": "description"
},
{
"RoleId": "b65eecd7-d551-4706-af7a-51d8e4d5093f",
"ShortDesc": "description"
},
{
"RoleId": "fbcea65a-5b75-409c-b722-3cb4306c8471",
"ShortDesc": "description"
},
{
"RoleId": "fdbc73b2-9fbb-4f3a-a087-3ec41a6800f9",
"ShortDesc": "description"
},
{
"RoleId": "360ae291-f8dd-430d-bb1f-ff04bada68c7",
"ShortDesc": "description"
},
{
"RoleId": "e363780b-26ae-4580-8b13-22d24fd098d8",
"ShortDesc": "description"
},
{
"RoleId": "4b3d37a4-4c8d-42f5-9378-52b0ab6ede30",
"ShortDesc": "description"
}
]
}
然后,您可以使用这些代码将JSON字符串转换为Role列表。
PS:您应该使用GSON lib来帮助您完成这项工作,您可以获得有关gson here的信息。将此jar添加到项目路径中,并使用代码
public static void main(String[] args) throws FileNotFoundException {
Gson gson = new Gson();
String json = readFromFile(new File("json.txt"));
GObj result = gson.fromJson(json, GObj.class);
System.out.println(result);
}
static String readFromFile(File file) throws FileNotFoundException {
Scanner scanner = new Scanner(new FileInputStream(file));
StringBuilder builder = new StringBuilder();
while (scanner.hasNext()) {
builder.append(scanner.nextLine());
}
scanner.close();
return builder.toString();
}
static class GObj {
public LinkedList<Role> getJsonTableResult;
@Override
public String toString() {return "GObj [getJsonTableResult=" + getJsonTableResult + "]";}
}
static class Role {
public String RoleId;
public String ShortDesc;
@Override
public String toString() {return "Role [RoleId=" + RoleId + ", ShortDesc=" + ShortDesc + "]";}
}
我从文件中读到的是你的json字符串。