本文介绍了杰克逊将JSON字符串转换为Java对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这可能是标题说明一切的问题之一.

This is probably one of those questions where the title says it all.

Jackson库中的ObjectMapper的readValue(file, class)方法使我非常着迷,该方法从文件中读取JSON字符串并将其分配给对象.

I am quite fascinated by the ObjectMapper's readValue(file, class) method, found within the Jackson library which reads a JSON string from a file and assigns it to an object.

我很好奇是否可以通过简单地从字符串中获取JSON并将其应用于对象来做到这一点.

I'm curious if this is possible to do by simply getting JSON from a string and applying it to an object.

某种替代性readValue()方法,该方法采用 String 而不是文件,并将其分配给对象?

Some sort of alternative readValue() method, which takes a String, instead of a file, and assigns it to an object?

例如,默认的readValue(file, class)方法如下所示:

For instance, while the default readValue(file, class) method looks like this:

ObjectMapper mapper = new ObjectMapper();
Student student = mapper.readValue("C:\\student.json", Student.class);

我想知道杰克逊(Jackson)中是否有某种方法可以实现以下目的:

I was wondering if there was some method in Jackson, which allowed the following:

ObjectMapper mapper = new ObjectMapper();
Student student = mapper.readValue("{\"id\":100,\"firstName\":\"Adam\"}", Student.class);

第二个示例使用一个字符串和一个类的对象,而第一个示例使用一个文件和一个类的对象.

The second example takes a string and an object of a class while the first one takes a file and an object of a class.

我只想剪掉中间人,在这种情况下,就是文件.

I just want to cut out the middle man, in this case, the file.

这是可行的吗,还是在Jackson的约束范围内不存在这种方法?

Is this doable or does no such method exist within the constraints of Jackson?

推荐答案

尝试一下,

您不能像这样做那样创建新的字符串.

You can't create a new string like your doing.

    String string = "{\"id\":100,\"firstName\":\"Adam\"}";
    Student student = mapper.readValue(string, Student.class);

这篇关于杰克逊将JSON字符串转换为Java对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-13 08:10