Java 没有从字符串值 ('') 反序列化的字符串参数构造函数/工厂方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/45110371/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
No String-argument constructor/factory method to deserialize from String value ('')
提问by Stephen
I'm running into a json parsing issue when using the ObjectMapper
class from the com.fasterxml.Hymanson.databind
package, and the error that I'm getting is:
我在使用包中的ObjectMapper
类时遇到了 json 解析问题com.fasterxml.Hymanson.databind
,我得到的错误是:
com.fasterxml.Hymanson.databind.JsonMappingException: Can not construct instance of com.graybar.utilities.ups.beans.Address: no String-argument constructor/factory method to deserialize from String value ('')
The web application where this problem is occurring is a Spring MVC application using an AngularJS front end, but I can duplicate the issue with a much smaller, all java program. Here are my beans:
发生此问题的 Web 应用程序是一个使用 AngularJS 前端的 Spring MVC 应用程序,但我可以用一个更小的全 java 程序来复制这个问题。这是我的豆子:
Shipment.java
Shipment.java
@JsonIgnoreProperties(ignoreUnknown = true)
public class Shipment {
@JsonProperty("Activity")
private ArrayList<Activity> activity;
public ArrayList<Activity> getActivity() {
return activity;
}
public void setActivity(ArrayList<Activity> activity) {
this.activity = activity;
}
}
Activity.java
活动.java
@JsonIgnoreProperties(ignoreUnknown = true)
public class Activity {
@JsonProperty("ActivityLocation")
private ArrayList<ActivityLocation> activityLocation;
public ArrayList<ActivityLocation> getActivityLocation() {
return activityLocation;
}
public void setActivityLocation(ArrayList<ActivityLocation> activityLocation) {
this.activityLocation = activityLocation;
}
}
ActivityLocation.java
ActivityLocation.java
@JsonIgnoreProperties(ignoreUnknown = true)
public class ActivityLocation {
@JsonProperty("Address")
private Address address;
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
}
Address.java
地址.java
@JsonIgnoreProperties(ignoreUnknown = true)
public class Address {
@JsonProperty("City")
private String city;
@JsonProperty("StateProvinceCode")
private String stateProvinceCode;
@JsonProperty("CountryCode")
private String countryCode;
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getCountryCode() {
return countryCode;
}
public void setCountryCode(String countryCode) {
this.countryCode = countryCode;
}
public String getStateProvinceCode() {
return stateProvinceCode;
}
public void setStateProvinceCode(String stateProvinceCode) {
this.stateProvinceCode = stateProvinceCode;
}
}
Here is the code where I can properly map the json:
这是我可以正确映射json的代码:
public static void main(String[] args) {
String jsonMessage = "" +
"{" +
" \"Activity\": [{ " +
" \"ActivityLocation\": { " +
" \"Address\": { " +
" \"City\": \"Hana\", " +
" \"StateProvinceCode\": \"Hi\", " +
" \"CountryCode\": \"US\" " +
" } " +
" } " +
" }, " +
" { " +
" \"ActivityLocation\": { " +
" \"Address\": { " +
" \"City\": \"Honolulu\", " +
" \"StateProvinceCode\": \"Hi\", " +
" \"CountryCode\": \"US\" " +
" } " +
" } " +
" }] " +
"} ";
try {
ObjectMapper mapper = new ObjectMapper();
mapper.enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY);
Shipment shipment = mapper.readValue(jsonMessage, Shipment.class);
System.out.println("shipment.toString = " + shipment.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
When adjusting the data in the jsonMessage
var is when I run into the error that I mentioned above:
在调整jsonMessage
var 中的数据时,我遇到了上面提到的错误:
"{" +
" \"Activity\": [{ " +
" \"ActivityLocation\": { " +
" \"Address\": { " +
" \"City\": \"Hana\", " +
" \"StateProvinceCode\": \"Hi\", " +
" \"CountryCode\": \"US\" " +
" } " +
" } " +
" }, " +
" { " +
" \"ActivityLocation\": { " +
" \"Address\": \"\" " +
" } " +
" } " +
" }] " +
"} ";
So, the problem happens when changing the json from this:
因此,从这里更改 json 时会发生问题:
{
"ActivityLocation": {
"Address": {
"City": "Honolulu",
"StateProvinceCode": "Hi",
"CountryCode": "US"
}
}
}]
to this:
对此:
{
"ActivityLocation": {
"Address": ""
}
}
Instead of sending values for my Address
bean, I'm getting just an empty string. Unfortunately, I'm receiving my data from a third party and have no control over the data I receive.
我没有为我的Address
bean发送值,而是得到一个空字符串。不幸的是,我从第三方接收我的数据并且无法控制我收到的数据。
Is there an annotation that needs to be added to be able to handle this?
是否需要添加注释才能处理此问题?
采纳答案by Abhijit Sarkar
Try setting mapper.configure(DeserializationConfig.Feature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT, true)
尝试设置 mapper.configure(DeserializationConfig.Feature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT, true)
or
或者
mapper.enable(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT);
depending on your Hymanson version.
取决于您的Hyman逊版本。
回答by Herman XU
mapper.enable(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT);
My code work well just as the answer above. The reason is that the json from Hymanson is different with the json sent from controller.
我的代码运行良好,就像上面的答案一样。原因是 Hymanson 的 json 与控制器发送的 json 不同。
String test1= mapper.writeValueAsString(result1);
And the json is like(which can be deserialized normally):
而json就像(可以正常反序列化):
{"code":200,"message":"god","data":[{"nics":null,"status":null,"desktopOperatorType":null,"marker":null,"user_name":null,"user_group":null,"user_email":null,"product_id":null,"image_id":null,"computer_name":"AAAA","desktop_id":null,"created":null,"ip_address":null,"security_groups":null,"root_volume":null,"data_volumes":null,"availability_zone":null,"ou_name":null,"login_status":null,"desktop_ip":null,"ad_id":null},{"nics":null,"status":null,"desktopOperatorType":null,"marker":null,"user_name":null,"user_group":null,"user_email":null,"product_id":null,"image_id":null,"computer_name":"BBBB","desktop_id":null,"created":null,"ip_address":null,"security_groups":null,"root_volume":null,"data_volumes":null,"availability_zone":null,"ou_name":null,"login_status":null,"desktop_ip":null,"ad_id":null}]}
but the json send from the another service just like:
但是 json 从另一个服务发送,就像:
{"code":200,"message":"查询桌面列表成功","data":[{"nics":"","status":"","metadata":"","desktopOperatorType":"","marker":"","user_name":"csrgzbsjy","user_group":"ADMINISTRATORS","user_email":"","product_id":"","image_id":"","computer_name":"B-jiegou-all-15","desktop_id":"6360ee29-eb82-416b-aab8-18ded887e8ff","created":"2018-11-12T07:45:15.000Z","ip_address":"192.168.2.215","security_groups":"","root_volume":"","data_volumes":"","availability_zone":"","ou_name":"","login_status":"","desktop_ip":"","ad_id":""},{"nics":"","status":"","metadata":"","desktopOperatorType":"","marker":"","user_name":"glory_2147","user_group":"ADMINISTRATORS","user_email":"","product_id":"","image_id":"","computer_name":"H-pkpm-all-357","desktop_id":"709164e4-d3e6-495d-9c1e-a7b82e30bc83","created":"2018-11-09T09:54:09.000Z","ip_address":"192.168.2.235","security_groups":"","root_volume":"","data_volumes":"","availability_zone":"","ou_name":"","login_status":"","desktop_ip":"","ad_id":""}]}
You can notice the difference when dealing with the param without initiation. Be careful
在不启动的情况下处理参数时,您可以注意到差异。当心
回答by Andrii Plotnikov
Had this when I accidentally was calling
当我不小心打电话时有这个
mapper.convertValue(...)
instead of
代替
mapper.readValue(...)
So, just make sure you call correct method, since argument are same and IDE can find many things
所以,只要确保你调用了正确的方法,因为参数是相同的,IDE 可以找到很多东西
回答by papaRomik
This exception says that you are trying to deserialize the object "Address" from string "\"\"" instead of an object description like "{…}". The deserializer can't find a constructor of Address with String argument. You have to replace "" by {} to avoid this error.
此异常表示您正在尝试从字符串“\”\“”而不是像“{…}”这样的对象描述反序列化对象“Address”。反序列化器找不到带有 String 参数的 Address 构造函数。您必须将 "" 替换为 {} 以避免此错误。
回答by orly.sharon
I found a different way to handle this error. (the variables is according to the original question)
我找到了一种不同的方法来处理这个错误。(变量是根据原始问题)
JsonNode parsedNodes = mapper.readValue(jsonMessage , JsonNode.class);
Response response = xmlMapper.enable(ACCEPT_EMPTY_STRING_AS_NULL_OBJECT,ACCEPT_SINGLE_VALUE_AS_ARRAY )
.disable(FAIL_ON_UNKNOWN_PROPERTIES, FAIL_ON_IGNORED_PROPERTIES)
.convertValue(parsedNodes, Response.class);