且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-11-07 20:23:28

无需为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);