json到其他java对象的转换

mmvthczy  于 2021-07-24  发布在  Java
关注(0)|答案(2)|浏览(451)

如标题所示,我需要将json文件转换为java对象。我正在寻找解决这个问题的spring或java解决方案。
这是我的控制器类(稍后将进行重构)

  1. package pl.githubdetails.GithubDetails.presentation;
  2. import org.springframework.boot.json.GsonJsonParser;
  3. import org.springframework.web.bind.annotation.GetMapping;
  4. import org.springframework.web.bind.annotation.PathVariable;
  5. import org.springframework.web.bind.annotation.RequestMapping;
  6. import org.springframework.web.bind.annotation.RestController;
  7. import pl.githubdetails.GithubDetails.applcation.RepositoryDetailsDTO;
  8. import java.io.IOException;
  9. import java.net.URI;
  10. import java.net.http.HttpClient;
  11. import java.net.http.HttpRequest;
  12. import java.net.http.HttpResponse;
  13. import java.text.MessageFormat;
  14. @RestController
  15. @RequestMapping("/repositories")
  16. public class DetailsController
  17. {
  18. final String uriTemplate = "https://api.github.com/repos/{0}/{1}";
  19. @GetMapping(value = "/{owner}/{repositoryName}")
  20. RepositoryDetailsDTO getRepositoryDetails(@PathVariable String owner, @PathVariable String repositoryName) throws IOException, InterruptedException {
  21. RepositoryDetailsDTO repositoryDetailsDTO = new RepositoryDetailsDTO();
  22. String uri = MessageFormat.format(uriTemplate, owner, repositoryName);
  23. HttpClient httpClient = HttpClient.newHttpClient();
  24. HttpRequest request = HttpRequest.newBuilder()
  25. .GET()
  26. .uri(URI.create(uri))
  27. .build();
  28. HttpResponse<String> httpResponse = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
  29. System.out.println(httpResponse.body());
  30. return null;
  31. }
  32. }

json响应示例:

  1. [
  2. {
  3. "id": 1296269,
  4. "node_id": "MDEwOlJlcG9zaXRvcnkxMjk2MjY5",
  5. "name": "Hello-World",
  6. "full_name": "octocat/Hello-World",
  7. "owner": {
  8. "login": "octocat",
  9. "id": 1,
  10. "node_id": "MDQ6VXNlcjE=",
  11. "avatar_url": "https://github.com/images/error/octocat_happy.gif",
  12. "gravatar_id": "",
  13. "url": "https://api.github.com/users/octocat",
  14. "html_url": "https://github.com/octocat",
  15. "followers_url": "https://api.github.com/users/octocat/followers",
  16. "following_url": "https://api.github.com/users/octocat/following{/other_user}",
  17. "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}",
  18. "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}",
  19. "subscriptions_url": "https://api.github.com/users/octocat/subscriptions",
  20. "organizations_url": "https://api.github.com/users/octocat/orgs",
  21. "repos_url": "https://api.github.com/users/octocat/repos",
  22. "events_url": "https://api.github.com/users/octocat/events{/privacy}",
  23. "received_events_url": "https://api.github.com/users/octocat/received_events",
  24. "type": "User",
  25. "site_admin": false
  26. },
  27. "private": false,
  28. "html_url": "https://github.com/octocat/Hello-World",
  29. "description": "This your first repo!",
  30. "fork": false,
  31. "url": "https://api.github.com/repos/octocat/Hello-World",
  32. "archive_url": "https://api.github.com/repos/octocat/Hello-World/{archive_format}{/ref}",
  33. "assignees_url": "https://api.github.com/repos/octocat/Hello-World/assignees{/user}",
  34. "blobs_url": "https://api.github.com/repos/octocat/Hello-World/git/blobs{/sha}",
  35. "branches_url": "https://api.github.com/repos/octocat/Hello-World/branches{/branch}",
  36. "collaborators_url": "https://api.github.com/repos/octocat/Hello-World/collaborators{/collaborator}",
  37. "comments_url": "https://api.github.com/repos/octocat/Hello-World/comments{/number}",
  38. "commits_url": "https://api.github.com/repos/octocat/Hello-World/commits{/sha}",
  39. "compare_url": "https://api.github.com/repos/octocat/Hello-World/compare/{base}...{head}",
  40. "contents_url": "https://api.github.com/repos/octocat/Hello-World/contents/{+path}",
  41. "contributors_url": "https://api.github.com/repos/octocat/Hello-World/contributors",
  42. "deployments_url": "https://api.github.com/repos/octocat/Hello-World/deployments",
  43. "downloads_url": "https://api.github.com/repos/octocat/Hello-World/downloads",
  44. "events_url": "https://api.github.com/repos/octocat/Hello-World/events",
  45. "forks_url": "https://api.github.com/repos/octocat/Hello-World/forks",
  46. "git_commits_url": "https://api.github.com/repos/octocat/Hello-World/git/commits{/sha}",
  47. "git_refs_url": "https://api.github.com/repos/octocat/Hello-World/git/refs{/sha}",
  48. "git_tags_url": "https://api.github.com/repos/octocat/Hello-World/git/tags{/sha}",
  49. "git_url": "git:github.com/octocat/Hello-World.git",
  50. "issue_comment_url": "https://api.github.com/repos/octocat/Hello-World/issues/comments{/number}",
  51. "issue_events_url": "https://api.github.com/repos/octocat/Hello-World/issues/events{/number}",
  52. "issues_url": "https://api.github.com/repos/octocat/Hello-World/issues{/number}",
  53. "keys_url": "https://api.github.com/repos/octocat/Hello-World/keys{/key_id}",
  54. "labels_url": "https://api.github.com/repos/octocat/Hello-World/labels{/name}",
  55. "languages_url": "https://api.github.com/repos/octocat/Hello-World/languages",
  56. "merges_url": "https://api.github.com/repos/octocat/Hello-World/merges",
  57. "milestones_url": "https://api.github.com/repos/octocat/Hello-World/milestones{/number}",
  58. "notifications_url": "https://api.github.com/repos/octocat/Hello-World/notifications{?since,all,participating}",
  59. "pulls_url": "https://api.github.com/repos/octocat/Hello-World/pulls{/number}",
  60. "releases_url": "https://api.github.com/repos/octocat/Hello-World/releases{/id}",
  61. "ssh_url": "git@github.com:octocat/Hello-World.git",
  62. "stargazers_url": "https://api.github.com/repos/octocat/Hello-World/stargazers",
  63. "statuses_url": "https://api.github.com/repos/octocat/Hello-World/statuses/{sha}",
  64. "subscribers_url": "https://api.github.com/repos/octocat/Hello-World/subscribers",
  65. "subscription_url": "https://api.github.com/repos/octocat/Hello-World/subscription",
  66. "tags_url": "https://api.github.com/repos/octocat/Hello-World/tags",
  67. "teams_url": "https://api.github.com/repos/octocat/Hello-World/teams",
  68. "trees_url": "https://api.github.com/repos/octocat/Hello-World/git/trees{/sha}",
  69. "clone_url": "https://github.com/octocat/Hello-World.git",
  70. "mirror_url": "git:git.example.com/octocat/Hello-World",
  71. "hooks_url": "https://api.github.com/repos/octocat/Hello-World/hooks",
  72. "svn_url": "https://svn.github.com/octocat/Hello-World",
  73. "homepage": "https://github.com",
  74. "language": null,
  75. "forks_count": 9,
  76. "stargazers_count": 80,
  77. "watchers_count": 80,
  78. "size": 108,
  79. "default_branch": "master",
  80. "open_issues_count": 0,
  81. "is_template": false,
  82. "topics": [
  83. "octocat",
  84. "atom",
  85. "electron",
  86. "api"
  87. ],
  88. "has_issues": true,
  89. "has_projects": true,
  90. "has_wiki": true

我想把它转换成这样一个类:

  1. @Data
  2. @AllArgsConstructor
  3. @NoArgsConstructor
  4. public class RepositoryDetailsDTO
  5. {
  6. String full_name;
  7. String description;
  8. String cloneUrl;
  9. String stars;
  10. String createdAt;
  11. }

你知道我怎么做吗?我在寻找最理想的方法来做到这一点。谢谢你的回答。顺便说一句,http客户端目前运行良好,但仅适用于字符串响应。我试着

  1. HttpResponse<RepositoryDetailsDTO> httpResponse = httpClient.send(request,HttpResponse.BodyHandlers.replacing(repositoryDetailsDTO));

但没用。

5jvtdoz2

5jvtdoz21#

我建议为您的json数据创建一个pojo如果您知道您将在json中收到的字段,您可以从http://www.jsonschema2pojo.org/
休息如下
示例.java

  1. import com.fasterxml.jackson.annotation.JsonIgnore;
  2. import com.fasterxml.jackson.annotation.JsonProperty;
  3. import lombok.Data;
  4. import java.util.HashMap;
  5. import java.util.List;
  6. import java.util.Map;
  7. @Data
  8. public class Example {
  9. private Integer id;
  10. private String node_id;
  11. private String name;
  12. private String full_name;
  13. private Owner owner;
  14. @JsonProperty("private")
  15. private Boolean _private;
  16. private String html_url;
  17. private String description;
  18. private Boolean fork;
  19. private String url;
  20. private String archive_url;
  21. private String assignees_url;
  22. private String blobs_url;
  23. private String branches_url;
  24. private String collaborators_url;
  25. private String comments_url;
  26. private String commits_url;
  27. private String compare_url;
  28. private String contents_url;
  29. private String contributors_url;
  30. private String deployments_url;
  31. private String downloads_url;
  32. private String events_url;
  33. private String forks_url;
  34. private String git_commits_url;
  35. private String git_refs_url;
  36. private String git_tags_url;
  37. private String git_url;
  38. private String issue_comment_url;
  39. private String issue_events_url;
  40. private String issues_url;
  41. private String keys_url;
  42. private String labels_url;
  43. private String languages_url;
  44. private String merges_url;
  45. private String milestones_url;
  46. private String notifications_url;
  47. private String pulls_url;
  48. private String releases_url;
  49. private String ssh_url;
  50. private String stargazers_url;
  51. private String statuses_url;
  52. private String subscribers_url;
  53. private String subscription_url;
  54. private String tags_url;
  55. private String teams_url;
  56. private String trees_url;
  57. private String clone_url;
  58. private String mirror_url;
  59. private String hooks_url;
  60. private String svn_url;
  61. private String homepage;
  62. private Object language;
  63. private Integer forks_count;
  64. private Integer stargazers_count;
  65. private Integer watchers_count;
  66. private Integer size;
  67. private String default_branch;
  68. private Integer open_issues_count;
  69. private Boolean is_template;
  70. private List<String> topics = null;
  71. private Boolean has_issues;
  72. private Boolean has_projects;
  73. private Boolean has_wiki;
  74. @JsonIgnore
  75. private Map<String, Object> additionalProperties = new HashMap<String, Object>();
  76. }

所有者.java

  1. import com.fasterxml.jackson.annotation.JsonIgnore;
  2. import com.fasterxml.jackson.annotation.JsonProperty;
  3. import lombok.Data;
  4. import java.util.HashMap;
  5. import java.util.Map;
  6. @Data
  7. public class Owner {
  8. @JsonProperty("login")
  9. private String login;
  10. @JsonProperty("id")
  11. private Integer id;
  12. @JsonProperty("node_id")
  13. private String nodeId;
  14. @JsonProperty("avatar_url")
  15. private String avatarUrl;
  16. @JsonProperty("gravatar_id")
  17. private String gravatarId;
  18. @JsonProperty("url")
  19. private String url;
  20. @JsonProperty("html_url")
  21. private String htmlUrl;
  22. @JsonProperty("followers_url")
  23. private String followersUrl;
  24. @JsonProperty("following_url")
  25. private String followingUrl;
  26. @JsonProperty("gists_url")
  27. private String gistsUrl;
  28. @JsonProperty("starred_url")
  29. private String starredUrl;
  30. @JsonProperty("subscriptions_url")
  31. private String subscriptionsUrl;
  32. @JsonProperty("organizations_url")
  33. private String organizationsUrl;
  34. @JsonProperty("repos_url")
  35. private String reposUrl;
  36. @JsonProperty("events_url")
  37. private String eventsUrl;
  38. @JsonProperty("received_events_url")
  39. private String receivedEventsUrl;
  40. @JsonProperty("type")
  41. private String type;
  42. @JsonProperty("site_admin")
  43. private Boolean siteAdmin;
  44. @JsonIgnore
  45. private Map<String, Object> additionalProperties = new HashMap<String, Object>();

}
repositorydetailsdto.java文件

  1. import lombok.Data;
  2. @Data
  3. public class RepositoryDetailsDTO {
  4. String full_name;
  5. String description;
  6. String clone_url;
  7. String stars;
  8. String createdAt;
  9. }

主要类别

  1. import com.fasterxml.jackson.databind.ObjectMapper;
  2. import org.apache.commons.beanutils.BeanUtils;
  3. import java.nio.file.Files;
  4. import java.nio.file.Paths;
  5. public class JSONPractise {
  6. public static void main(String[] args) throws Exception {
  7. String file = "DataFile.json";
  8. String jsonStr = readFileAsString(file);
  9. ObjectMapper mapper = new ObjectMapper();
  10. Example example = mapper.readValue(jsonStr, Example.class);
  11. RepositoryDetailsDTO repositoryDetailsDTO = new RepositoryDetailsDTO();
  12. BeanUtils.copyProperties(repositoryDetailsDTO, example);
  13. System.out.println(example.toString());
  14. System.out.println(repositoryDetailsDTO.toString());
  15. }
  16. public static String readFileAsString(String file)throws Exception
  17. {
  18. return new String(Files.readAllBytes(Paths.get(file)));
  19. }
  20. }

输出:

  1. Example(id=1296269, node_id=MDEwOlJlcG9zaXRvcnkxMjk2MjY5, name=Hello-World, full_name=octocat/Hello-World, owner=Owner(login=octocat, id=1, nodeId=MDQ6VXNlcjE=, avatarUrl=https://github.com/images/error/octocat_happy.gif, gravatarId=, url=https://api.github.com/users/octocat, htmlUrl=https://github.com/octocat, followersUrl=https://api.github.com/users/octocat/followers, followingUrl=https://api.github.com/users/octocat/following{/other_user}, gistsUrl=https://api.github.com/users/octocat/gists{/gist_id}, starredUrl=https://api.github.com/users/octocat/starred{/owner}{/repo}, subscriptionsUrl=https://api.github.com/users/octocat/subscriptions, organizationsUrl=https://api.github.com/users/octocat/orgs, reposUrl=https://api.github.com/users/octocat/repos, eventsUrl=https://api.github.com/users/octocat/events{/privacy}, receivedEventsUrl=https://api.github.com/users/octocat/received_events, type=User, siteAdmin=false, additionalProperties={}), _private=false, html_url=https://github.com/octocat/Hello-World, description=This your first repo!, fork=false, url=https://api.github.com/repos/octocat/Hello-World, archive_url=https://api.github.com/repos/octocat/Hello-World/{archive_format}{/ref}, assignees_url=https://api.github.com/repos/octocat/Hello-World/assignees{/user}, blobs_url=https://api.github.com/repos/octocat/Hello-World/git/blobs{/sha}, branches_url=https://api.github.com/repos/octocat/Hello-World/branches{/branch}, collaborators_url=https://api.github.com/repos/octocat/Hello-World/collaborators{/collaborator}, comments_url=https://api.github.com/repos/octocat/Hello-World/comments{/number}, commits_url=https://api.github.com/repos/octocat/Hello-World/commits{/sha}, compare_url=https://api.github.com/repos/octocat/Hello-World/compare/{base}...{head}, contents_url=https://api.github.com/repos/octocat/Hello-World/contents/{+path}, contributors_url=https://api.github.com/repos/octocat/Hello-World/contributors, deployments_url=https://api.github.com/repos/octocat/Hello-World/deployments, downloads_url=https://api.github.com/repos/octocat/Hello-World/downloads, events_url=https://api.github.com/repos/octocat/Hello-World/events, forks_url=https://api.github.com/repos/octocat/Hello-World/forks, git_commits_url=https://api.github.com/repos/octocat/Hello-World/git/commits{/sha}, git_refs_url=https://api.github.com/repos/octocat/Hello-World/git/refs{/sha}, git_tags_url=https://api.github.com/repos/octocat/Hello-World/git/tags{/sha}, git_url=git:github.com/octocat/Hello-World.git, issue_comment_url=https://api.github.com/repos/octocat/Hello-World/issues/comments{/number}, issue_events_url=https://api.github.com/repos/octocat/Hello-World/issues/events{/number}, issues_url=https://api.github.com/repos/octocat/Hello-World/issues{/number}, keys_url=https://api.github.com/repos/octocat/Hello-World/keys{/key_id}, labels_url=https://api.github.com/repos/octocat/Hello-World/labels{/name}, languages_url=https://api.github.com/repos/octocat/Hello-World/languages, merges_url=https://api.github.com/repos/octocat/Hello-World/merges, milestones_url=https://api.github.com/repos/octocat/Hello-World/milestones{/number}, notifications_url=https://api.github.com/repos/octocat/Hello-World/notifications{?since,all,participating}, pulls_url=https://api.github.com/repos/octocat/Hello-World/pulls{/number}, releases_url=https://api.github.com/repos/octocat/Hello-World/releases{/id}, ssh_url=git@github.com:octocat/Hello-World.git, stargazers_url=https://api.github.com/repos/octocat/Hello-World/stargazers, statuses_url=https://api.github.com/repos/octocat/Hello-World/statuses/{sha}, subscribers_url=https://api.github.com/repos/octocat/Hello-World/subscribers, subscription_url=https://api.github.com/repos/octocat/Hello-World/subscription, tags_url=https://api.github.com/repos/octocat/Hello-World/tags, teams_url=https://api.github.com/repos/octocat/Hello-World/teams, trees_url=https://api.github.com/repos/octocat/Hello-World/git/trees{/sha}, clone_url=https://github.com/octocat/Hello-World.git, mirror_url=git:git.example.com/octocat/Hello-World, hooks_url=https://api.github.com/repos/octocat/Hello-World/hooks, svn_url=https://svn.github.com/octocat/Hello-World, homepage=https://github.com, language=null, forks_count=9, stargazers_count=80, watchers_count=80, size=108, default_branch=master, open_issues_count=0, is_template=false, topics=[octocat, atom, electron, api], has_issues=true, has_projects=true, has_wiki=true, additionalProperties={})
  2. RepositoryDetailsDTO(full_name=octocat/Hello-World, description=This your first repo!, clone_url=https://github.com/octocat/Hello-World.git, stars=null, createdAt=null)
展开查看全部
rsl1atfo

rsl1atfo2#

问题解决了我发现了这样的东西:

  1. repositoryDetailsDTO = new ObjectMapper()
  2. .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
  3. .readValue(httpResponse.body(), RepositoryDetailsDTO.class);

相关问题