使用 Jackson 与嵌套 JSON 的对象相互转换

我有一个实体类,下面有两个字符串字段:名称和描述。描述字段将包含一个原始 JSON 值,例如 { "abc": 123 }


@Getter

@Setter

public class Entity {

    private String name;


    @JsonRawValue

    private String descriptionJson; 

}

我在下面使用 Jackson 序列化和反序列化得到了简单的测试代码:


Entity ent = new Entity();

ent.setName("MyName");

ent.setDescriptionJson("{ \"abc\": 123 }");


// Convert Object to JSON string

String json = mapper.writeValueAsString(ent);


// Convert JSON string back to object

Entity ent2 = mapper.readValue(json, Entity.class);

转换 Object -> JSON 时,描述字符串是嵌套的,因为设置了 @JsonRawValue:


{"name":"MyName","descriptionJson":{ "abc": 123 }}

但是,当我调用 Jackson mapper.readValue 函数将 JSON 字符串读回实体对象时,出现异常:


com.fasterxml.jackson.databind.exc.MismatchedInputException:

Cannot deserialize instance of `java.lang.String` out of START_OBJECT token 

at [Source: (String)"{"name":"MyName","descriptionJson":{ "abc": 123 }}"; line: 1, column: 36] (through reference chain: com.test.Entity["descriptionJson"])

鉴于存在 @JsonRawValue 注释,您建议如何将创建的 JSON 字符串编组回实体对象?我还缺少另一个注释吗?


慕姐4208626
浏览 469回答 3
3回答

尚方宝剑之说

仅用于序列化端,但在此问题中,您可以这样做:@Getter@Setterpublic class Entity {    private String name;    @JsonRawValue    private String descriptionJson;    @JsonProperty(value = "descriptionJson")    public void setDescriptionJsonRaw(JsonNode node) {        this.descriptionJson = node.toString();    }}

偶然的你

对于我的一项要求,我使用字段类型作为 Map 来按原样存储 Json。这样我就能够将嵌套的 JSOn 作为 Map 读取,当我将对象序列化为 JSON 时,它正确出现。下面是示例。实体.javaimport com.fasterxml.jackson.annotation.JsonIgnoreProperties;import lombok.Data;import java.util.HashMap;import java.util.Map;@Data@JsonIgnoreProperties(ignoreUnknown = true)public class Entity {&nbsp; &nbsp; public int id=0;&nbsp; &nbsp; public String itemName="";&nbsp; &nbsp; public Map<String,String> owner=new HashMap<>();}临时文件import com.fasterxml.jackson.databind.ObjectMapper;import java.io.IOException;public class Temp {public static void main(String[] args){&nbsp; &nbsp; ObjectMapper objectMapper= new ObjectMapper();&nbsp; &nbsp; try {&nbsp; &nbsp; &nbsp; &nbsp; Entity entity&nbsp;=objectMapper.readValue(Temp.class.getResource("sample.json"), Entity.class);&nbsp; &nbsp; &nbsp; &nbsp; System.out.println(entity);&nbsp; &nbsp; &nbsp; &nbsp; String json=objectMapper.writeValueAsString(entity);&nbsp; &nbsp; &nbsp; &nbsp; System.out.println(json);&nbsp; &nbsp; } catch (IOException e) {&nbsp; &nbsp; &nbsp; &nbsp; e.printStackTrace();&nbsp; &nbsp; }&nbsp; &nbsp; }}示例.json{&nbsp; "id": 1,&nbsp; "itemName": "theItem",&nbsp; "owner": {&nbsp; &nbsp; "id": 2,&nbsp; &nbsp; "name": "theUser"&nbsp; }}

MMMHUHU

您可以ObjectMapper从 Jackson 2使用,如下所示:ObjectMapper mapper = new ObjectMapper();String jsonStr = "sample json string"; // populate this as requiredMyClass obj = mapper.readValue(jsonStr,MyClass.class)尝试在描述 json 的值中转义花括号。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java