繁体   English   中英

无法将带有@字段的 Json 转换为自定义 java Object

[英]Not able to convert Json with @ in field to custom java Object

在我的 java 代码中,

我的 BookRequestTO class

@Getter
@Builder
@EqualsAndHashCode
@ToString
@NoArgsConstructor
@AllArgsConstructor

public class BookRequestTO {
    private String id;

    @NotNull(message = Constants.FUNCTION_NULL)
    @Valid
    private BookInfo function;

    private List<String> parameters;
}

我的 BookInfo class

@Getter
@Builder
@EqualsAndHashCode
@ToString
@NoArgsConstructor
@AllArgsConstructor
public class BookInfo {

    @NotEmpty(message = Constants.TYPE_NULL)
    @JsonProperty(value = "@type")
    private String type;

    @NotEmpty(message = Constants.ACTION_NULL)
    private String name;
}

我的目标是将其字段中带有 @ 的 json 转换为一些自定义 object

我尝试了以下两种方法:

方法一:

import com.google.gson.Gson;
import org.json.JSONArray;
import org.json.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

JSONObject jsonRequest = new JSONObject();
jsonRequest.put("@type", "education");
jsonRequest.put("name", "Geography");

JSONObject bookRequestToJson = new JSONObject();
bookRequestToJson.put("id", "1234");
bookRequestToJson.put("function", jsonRequest);
bookRequestToJson.put("parameters", new JSONArray());

BookRequestTO bookRequestTO = new ObjectMapper().readValue(bookRequestToJson.toString(), BookRequestTO.class);

System.out.println("BEFORE ObjectWriter: bookRequestTO " + bookRequestTO);

这里@type被忽略了,我的回复中只有type=education ,正如你在下面看到的,我期望它是@type=education

BEFORE ObjectWriter: bookRequestTO BookRequestTO(id=1234, function=BookInfo(type=education, name=Geography), parameters=[])

具有相同代码的方法2:

ObjectWriter ow1 = new ObjectMapper().writer().withDefaultPrettyPrinter();
String request = ow1.writeValueAsString(bookRequestToJson.toString()).replaceAll("\\\\", "");
request = request.substring(1, request.length() - 1);
System.out.println("AFTER ObjectWriter: bookRequestTO " + request);
        
BookRequestTO bookRequestTO1 = new Gson().fromJson(request, BookRequestTO.class);
System.out.println("AFTER Gson: bookRequestTO " + bookRequestTO1);

运行下面的代码后是output,这里它忽略了实际的类型值,它变成了null

AFTER ObjectWriter: bookRequestTO {"function":{"@type":"education","name":"Geography"},"id":"1234","parameters":[]}
AFTER Gson: bookRequestTO BookRequestTO(id=1234, function=BookInfo(type=null, name=Geography), parameters=[])

有人可以帮忙吗? 或者 java 自定义 object 中是否不可能有 @。

这是因为您没有使用 Jackson 的 ObjectMapper 将 output BookInfo 作为 JSON 字符串。 在第一次尝试中,您使用的是 Lombok 生成的 toString() 方法,该方法无法识别 Jackson 注释@JsonProperty

在第二次尝试中,您使用 Jackson 成功写入 JSON 字符串,但您使用 GSon 读取和写入 BookInfo。 GSon 也无法识别 Jackson 的@JsonProperty注释,因此它将字段“type”视为“type”,并且在 JSON 字符串中看到字段“@type”时无法识别该字段。

如果要使用 GSon,则需要使用自己的注解: @SerializedName("@type")

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM