如何将以下json字符串转换为java对象? [英] How to convert the following json string to java object?

查看:523
本文介绍了如何将以下json字符串转换为java对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将以下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"}]}"

我的目标是轻松访问:

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

我听说过杰克逊,但我不确定如何使用它来装入json字符串我由于涉及mymusic列表,它不仅仅是关键值对。我怎么能用杰克逊来完成这个呢?或者如果杰克逊不是最好的话,我能有一些更简单的方法吗?

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);

这篇关于如何将以下json字符串转换为java对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆