How to convert the following json string to java object?(如何将以下 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 对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何将以下 json 字符串转换为 java 对象?
基础教程推荐
- 首次使用 Hadoop,MapReduce Job 不运行 Reduce Phase 2022-01-01
- Spring Boot Freemarker从2.2.0升级失败 2022-01-01
- 如何使用 Stream 在集合中拆分奇数和偶数以及两者的总和 2022-01-01
- Java 中保存最后 N 个元素的大小受限队列 2022-01-01
- 如何使用 Eclipse 检查调试符号状态? 2022-01-01
- 如何对 HashSet 进行排序? 2022-01-01
- 由于对所需库 rt.jar 的限制,对类的访问限制? 2022-01-01
- 如何在不安装整个 WTP 包的情况下将 Tomcat 8 添加到 Eclipse Kepler 2022-01-01
- 如何强制对超级方法进行多态调用? 2022-01-01
- 在螺旋中写一个字符串 2022-01-01