类
class PrintRequest {
private String data;
private String userImageBase64;
private String organizationImageBase64;
private String fileBase64;
//getters and setters
}
用
PrintRequest printRequest = gson.fromJson(request.getBody(), PrintRequest.class);
json
{
"data":{
"nazwaDostawcy":"nazwa dostawcy (opis)",
"nazwa":"Gniazdo przemysłowe, kątowe, 2p+E, 16A, 100...130 V AC, IP 44 ",
"kod":"val",
"kodEan":"val",
"kodWewnrtrzny":"val",
"cennaNetto":"val"
},
"fileBase64":""
}
就像在主题中一样,我理解为什么会收到此错误,但是我需要将
data
作为字符串返回。我如何实现我的目标?感谢帮助!
最佳答案
这是不创建自定义gson序列化的最简单方法。只需重写toString()方法
public class PrintRequest {
private Value data;
private String userImageBase64;
private String organizationImageBase64;
private String fileBase64;
//getters and setters
}
public class Value {
String nazwaDostawcy;
@Override
public String toString() {
return "Value{" +
"nazwaDostawcy='" + nazwaDostawcy + '\'' +
", nazwa='" + nazwa + '\'' +
", kod='" + kod + '\'' +
", kodEan='" + kodEan + '\'' +
", kodWewnrtrzny='" + kodWewnrtrzny + '\'' +
", cennaNetto='" + cennaNetto + '\'' +
", kategoria='" + kategoria + '\'' +
", opis='" + opis + '\'' +
", logo1='" + logo1 + '\'' +
", logo2='" + logo2 + '\'' +
'}';
}
String nazwa;
String kod;
String kodEan;
String kodWewnrtrzny;
String cennaNetto;
String kategoria;
String opis;
String logo1;
String logo2;
//getters and setters
}
用法:
PrintRequest printRequest = gson.fromJson(json,PrintRequest.class);
System.out.println(printRequest.getData()。toString());
UPD:
定制JsonDeserializer的解决方案
public class CustomJsonDeserializer implements JsonDeserializer<PrintRequest> {
@Override
public PrintRequest deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
PrintRequest printRequest = new PrintRequest();
JsonObject jsonObject = jsonElement.getAsJsonObject();
String dataStr="";
JsonObject jsonObjectData = jsonObject.getAsJsonObject("data");
for (Data data : Data.values()) {
dataStr+=(data.name() + ":" + jsonObjectData.get(data.name()).getAsString()+",\n");
}
printRequest.setData(dataStr);
return printRequest;
}
}
public enum Data {
nazwaDostawcy,
nazwa
}
public class PrintRequest {
private String data;
private String userImageBase64;
private String organizationImageBase64;
private String fileBase64;
//getters and setters
用法:
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES);
gsonBuilder.registerTypeAdapter(PrintRequest.class, new CustomJsonDeserializer());
Gson gson = gsonBuilder.create();
PrintRequest printRequest = gson.fromJson(json, PrintRequest.class);
System.out.println(printRequest.getData());
关于java - 应为字符串,但为BEGIN_OBJECT我必须返回字符串,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58953073/