Java 使用 JACKSON 读取 JSON 文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/50304313/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Read a JSON file using HymanSON
提问by Arnau Van Boschken ArnauB
I want to read a JSON file received.
我想读取收到的 JSON 文件。
That's the form of the JSON file:
这是 JSON 文件的格式:
{
"name": "list_name"
"items": [
{
"id": 4
},
{
"id": 3
},
{
"id": 2
},
]
}
I want to parse that JSON that represents a movie list, and the id's of the movies. I want to extract the ids and the name.
我想解析代表电影列表的 JSON 和电影的 id。我想提取 ID 和名称。
@PUT
@Path("/")
@Consumes(MediaType.APPLICATION_JSON)
public Response deleteMoviesFromList2(@Context HttpServletRequest req) Long movieListId) {
Long userId = getLoggedUser(req);
getLoggedUser(req);
final String json = "some JSON string";
final ObjectMapper mapper = new ObjectMapper();
return buildResponse(listMovieService.remove(??));
}
I want to extract the ids but I have no clue how to do it.
我想提取 ID,但我不知道该怎么做。
回答by DeepInJava
You can convert json string using ObjectMapper class like this.
您可以像这样使用 ObjectMapper 类转换 json 字符串。
ObjectMapper objectMapper = new ObjectMapper();
String carJson =
"{ \"brand\" : \"Mercedes\", \"doors\" : 5 }";
try {
Car car = objectMapper.readValue(carJson, Car.class);
System.out.println("car brand = " + car.getBrand());
System.out.println("car doors = " + car.getDoors());
} catch (IOException e) {
e.printStackTrace();
}
Here you can replace Car class with your custom Movie class and you are done.
在这里,您可以用自定义的 Movie 类替换 Car 类,然后就完成了。
回答by ernest_k
If you have a movie class defined, such as:
如果您定义了一个电影类,例如:
class Movie {
String id;
//getters
//setters
}
and a Movie list class:
和电影列表类:
class MovieList {
String name;
List<Movie> items;
//getters
//setters
}
Then you can use an object mapper with an inputStream:
然后你可以使用带有 inputStream 的对象映射器:
try(InputStream fileStream = new FileInputStream("movielist.json")) {
MovieList list = mapper.readValue(fileStream, MovieList.class);
}
ObjectMapper
's readValue has an overloaded version that takes an input stream, and that's the one used above.
ObjectMapper
的 readValue 有一个接受输入流的重载版本,这就是上面使用的那个。