簡體   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