gson 无法将字段中带有@的Json转换为自定义java对象

euoag5mw  于 2022-11-06  发布在  Java
关注(0)|答案(1)|浏览(222)

在我的java代码中,
我的BookRequestTO类

@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类

@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转换为某个自定义对象
我尝试了以下2种方法:

方法1:

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);

运行以下代码后的输出,此处忽略了实际的类型值,并将其设置为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自定义对象中不能有@。

sczxawaw

sczxawaw1#

这是因为您没有使用Jackson的ObjectMapper将BookInfo输出为JSON字符串。在第一次尝试中,您使用的是Lombok生成的toString()方法,该方法无法识别Jackson注解@JsonProperty
在第二次尝试中,您成功地使用Jackson编写了JSON字符串,但是您使用GSon读写了BookInfo。GSon也无法识别Jackson的@JsonProperty注解,因此它将字段“type”视为“type”,并且在JSON字符串中看到字段“@type”时无法识别它。
如果你想使用GSon,你需要使用它自己的注解:@SerializedName("@type") .

相关问题