一尘不染

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

json

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

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"}]}"

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

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

我听说过Jackson,但是由于涉及“
mymusic”列表,我不知道如何使用它来适应我拥有的json字符串,因为它不仅仅是键值对。如果杰克逊不是最好的选择,我该如何用杰克逊完成?


阅读 274

收藏
2020-07-27

共1个答案

一尘不染

为此,无需与GSON一起使用;杰克逊可以做普通的地图/列表:

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

或更方便的JSON树:

JsonNode rootNode = mapper.readTree(json);

顺便说一句,没有理由为什么您不能实际创建Java类并更方便地执行(IMO):

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);
2020-07-27