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

查看:33
本文介绍了如何将以下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"
    }
  ]
}"

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

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

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

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