无法将含@字段的JSON转换为自定义Java对象,求解决方案
含@字段的JSON转换为Java自定义对象的问题
我的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; }
尝试的两种方案及问题
方案1:使用Jackson的ObjectMapper
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);
执行输出:
BEFORE ObjectWriter: bookRequestTO BookRequestTO(id=1234, function=BookInfo(type=education, name=Geography), parameters=[])
这里@type字段已经映射到Java对象的type属性,但我误以为输出应该显示@type=education,不确定映射是否真的正确。
方案2:结合ObjectWriter与Gson
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);
执行输出:
AFTER ObjectWriter: bookRequestTO {"function":{"@type":"education","name":"Geography"},"id":"1234","parameters":[]} AFTER Gson: bookRequestTO BookRequestTO(id=1234, function=BookInfo(type=null, name=Geography), parameters=[])
这里用Gson转换后,BookInfo的type属性为null,没有正确映射@type字段。
疑问
请问如何正确实现含@字段的JSON到Java自定义对象的转换?Java是否支持此类映射?
内容的提问来源于stack exchange,提问作者user19817822
相关产品推荐
相关产品推荐

