迈克尔杰克逊mtv
ObjectMapper背景(ObjectMapper Background)
JSON is used in many applications to store and send data, the ability to parse and read this data is very important on your journey to becoming a skilled programmer. Before I knew about ObjectMapper, I would manually search for fields in a JSON by doing.
JSON在许多应用程序中用于存储和发送数据,在成为一名熟练的程序员的过程中,解析和读取此数据的能力非常重要。 在我了解ObjectMapper之前,我会通过手动搜索JSON中的字段。
String myVal = json.substring(json.indexOf(field)+ 1, lengthOfVal)
This is a gross and error prone way to get values from a JSON and when a senior dev on my team saw me doing this they showed me the light 🌤️. (The light being Jackson ObjectMapper)
这是从JSON获取值的一种粗略且容易出错的方法,当我团队中的一位资深开发人员看到我这样做时,他们向我展示了🌤️。 (光是杰克逊的ObjectMapper)

Jackson ObjectMapper的案例研究 (A Case Study for Jackson ObjectMapper)
Imagine it’s Friday night and your significant other and you are going to get dinner 🍽 . Unfortunately, your partner is very picky and by the time they decide on a place to eat, it’ll be time for breakfast 😭. Lucky for you the city you live in provides an API with all the restaurants in the town 😀.
想象一下,这是星期五晚上,而您是另一个重要的晚上,您将要去吃晚餐🍽。 不幸的是,您的伴侣很挑剔,等他们决定要吃饭的地方时,就该该吃早餐了。 幸运的是,您所居住的城市为该镇all中的所有餐馆提供API。
{"restaurants":
[
{
"id": "19ujjWJM219",
"cuisine": "Italian",
"name": "Pepe's",
"date":"08/22/2020",
"chefs": [
"Luca",
"Ferdinand",
"Mario"
],
"menu": {
"menuitem": [
{"name": "Pasta", "price": "10"},
{"name": "Pizza", "price": "12"},
{"name": "Chicken Parm", "price": "20"}
]
}
},
{
"id": "w8239dnJJS",
"cuisine": "Seafood",
"name": "The Catch",
"chefs": [
"Kyle",
"Alex"
],
"menu": {
"date":"07/12/2020",
"menuitem": [
{"name": "Salmon", "price": "20"},
{"name": "Lobster", "price": "30"},
{"name": "Shrimp", "price": "18"}
]
}
}
]
}
The only problem is, this is an ugly way to look at data 🤢. So lets make it easier to read by parsing the JSON to get only the name of the restaurant and the dishes 🍔🥗🍝 available 😁.
唯一的问题是,这是查看数据an的丑陋方式。 因此,通过解析JSON以仅获取餐厅的名称和可用的菜肴,我们将使其更易于阅读。

First we will need load the Jackson library into our project
首先,我们需要将Jackson库加载到我们的项目中
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.8</version>
</dependency>
put this within the <dependencies></dependencies> tags in your pom file for a maven project.
将其放在Maven项目的pom文件中的<dependencies> </ dependencies>标记内。
2. Next, let’s put in the basic code in our java program to read the json from a file.
2.接下来,让我们在Java程序中放入基本代码,以从文件中读取json。
public class ParseJson {
public static void main(String[] args) throws IOException {
File jsonFile = new File("src/main/java/parsejson/jsonExample");
String content = readFile(jsonFile);
}
public static String readFile(File file) throws IOException {
BufferedReader reader = new BufferedReader(new FileReader(file));
StringBuilder stringBuilder = new StringBuilder();
String line;
String ls = "\n";
while ((line = reader.readLine()) != null) {
stringBuilder.append(line);
stringBuilder.append(ls);
}
// delete the last new line separator
stringBuilder.deleteCharAt(stringBuilder.length() - 1);
reader.close();
return stringBuilder.toString();
}
}
This is basic file reading code to get the contents of our file as a string.
这是基本的文件读取代码,用于获取文件内容作为字符串。
In readFile(): We use a buffered file reader to append lines to a string builder while there is still a line to read and then return the resulting string (contents of the file).
在readFile()中:我们使用缓冲的文件读取器将行添加到字符串生成器,同时还有一行要读取,然后返回结果字符串(文件内容)。
In main(): We will create a File object using the path to our json from above. Then, we can call our newly made readFile() function to get the contents of the json in a string.
在main()中:我们将从上方使用json的路径创建一个File对象。 然后,我们可以调用新创建的readFile()函数以字符串形式获取json的内容。
3. Finally, we will add in the code to parse through the JSON and rip out the data we need 🤓.
3.最后,我们将添加代码以通过JSON进行解析,并提取所需的数据。
public class ParseJson {
public static void main(String[] args) throws IOException {
File jsonFile = new File("src/main/java/parsejson/jsonExample");
String content = readFile(jsonFile);
ObjectMapper objectMapper = new ObjectMapper();
JsonNode jsonNode = objectMapper.readTree(content);
jsonNode.get("restaurants").forEach(
(restaurant)->{restaurant.get("menu").get("menuitem").forEach(
(item)->{System.out.println(String.format("%s: %s %s", restaurant.get("name"), item.get("name"), item.get("price")));}
);
}
);
}
public static String readFile(File file) throws IOException {
BufferedReader reader = new BufferedReader(new FileReader(file));
StringBuilder stringBuilder = new StringBuilder();
String line;
String ls = "\n";
while ((line = reader.readLine()) != null) {
stringBuilder.append(line);
stringBuilder.append(ls);
}
// delete the last new line separator
stringBuilder.deleteCharAt(stringBuilder.length() - 1);
reader.close();
return stringBuilder.toString();
}
}
on line 9, we get the list of the restaurants in our city. on line 10 for each restaurant, we drill down and get the list of menu items. And on line 11, we print out a line containing the restaurant, dish name 🍽 and price 💰 for each dish available in this city 🏙️.
在第9行,我们获得了城市中的餐馆列表。 在每个餐厅的第10行,我们向下钻取并获得菜单项列表。 在第11行上,我们打印出一行,其中包含该城市🏙️中每种餐厅的餐厅,菜名🍽和价格💰。
The output of this code should be the following…
此代码的输出应为以下内容…
“Pepe’s”: “Pasta” “10”
“Pepe’s”: “Pizza” “12”
“Pepe’s”: “Chicken Parm” “20”
“The Catch”: “Salmon” “20”
“The Catch”: “Lobster” “30”
“The Catch”: “Shrimp” “18”
Ta-Da! you now know how to use Jackson to parse through JSON! 🎉 🎊 Now you have no reason to hack through JSON using string manipulations 😂 👍.
塔达! 您现在知道了如何使用Jackson来通过JSON进行解析! 现在您没有理由使用字符串操作来破解JSON。
翻译自: https://medium.com/dev-genius/easily-parse-json-with-the-powerful-jackson-objectmapper-c1fb35cb4730
迈克尔杰克逊mtv