如何将以下 json 字符串转换为 java 对象?

2022-01-31 00:00:00 json java jackson

我想将以下 JSON 字符串转换为 java 对象:

I want to convert the following JSON string to a java object:

String jsonString = "{
  "libraryname": "My Library",
  "mymusic": [
    {
      "Artist Name": "Aaron",
      "Song Name": "Beautiful"
    },
    {
      "Artist Name": "Britney",
      "Song Name": "Oops I did It Again"
    },
    {
      "Artist Name": "Britney",
      "Song Name": "Stronger"
    }
  ]
}"

我的目标是轻松访问它,例如:

My goal is to access it easily something like:

(e.g. MyJsonObject myobj = new MyJsonObject(jsonString)
myobj.mymusic[0].id would give me the ID, myobj.libraryname gives me "My Library").

我听说过 Jackson,但我不确定如何使用它来适应我拥有的 json 字符串,因为它不仅仅是键值对,因为mymusic";涉及的名单.我如何与 Jackson 一起完成此任务,或者如果 Jackson 不是最适合此任务,我是否有更简单的方法可以完成此任务?

I've heard of Jackson, but I am unsure how to use it to fit the json string I have since its not just key value pairs due to the "mymusic" list involved. How can I accomplish this with Jackson or is there some easier way I can accomplish this if Jackson is not the best for this?

推荐答案

不需要GSON;杰克逊可以做简单的地图/列表:

No need to go with GSON for this; Jackson can do either plain Maps/Lists:

ObjectMapper mapper = new ObjectMapper();
Map<String,Object> map = mapper.readValue(json, Map.class);

或更方便的 JSON 树:

or more convenient JSON Tree:

JsonNode rootNode = mapper.readTree(json);

顺便说一句,你没有理由不能真正创建 Java 类并更方便地执行它(IMO):

By the way, there is no reason why you could not actually create Java classes and do it (IMO) more conveniently:

public class Library {
  @JsonProperty("libraryname")
  public String name;

  @JsonProperty("mymusic")
  public List<Song> songs;
}
public class Song {
  @JsonProperty("Artist Name") public String artistName;
  @JsonProperty("Song Name") public String songName;
}

Library lib = mapper.readValue(jsonString, Library.class);

相关文章