有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

将多列json数据转换为java

我有一些用C#编写的web服务,它们执行一些基本的数据库访问,并返回带有信息的JSON字符串。我需要将其放入名为Role的对象数组中(每个Role表示数据库上的一行-RoleIdShortDesc

在web服务中,JSON是使用Jackson 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对象数组(包括RoleIdShortDesc字符串字段)?我是新来的JSON,到目前为止一直在努力反序列化它


共 (1) 个答案

  1. # 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字符串转换为角色列表

    PS:You should use GSON lib to help you do this job,you can get info about gson here. add this jar to your project path,and use the code

    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字符串