繁体   English   中英

如何使用 Jackson 的 ObjectMapper 将下面的 JSON 转换为 POJO

[英]How to convert below JSON to POJO using ObjectMapper of Jackson

我正在尝试使用Jackson的ObjectMapper类将下面的代码转换为JSON到POJO,但它抛出异常。 谁能帮我解决这个问题。 实际上 JSON 是由 UI 给出的,所以不能改变它的格式。 我需要使用 Jackson 库将此 JSON 解析为 java 对象。

JSON:data.json

{
    "0": {
        "location": "6",
        "userType": "1",
        "isActive": "1",
        "userId": "Shailesh@gmail.com"
    },
    "1": {
        "location": "7",
        "userType": "2",
        "isActive": "1",
        "userId": "Vikram@gmail.com"
    }
}

DTO:

public class UsersList {
    List<UserDetails> users;
}

public class UserDetails {
    private String userId;
    private String location;
    private String userType;
    private String isActive;

    public String getUserId() {
        return userId;
    }
    public void setUserId(String userId) {
        this.userId = userId;
    }
    public String getLocation() {
        return location;
    }
    public void setLocation(String location) {
        this.location = location;
    }
    public String getUserType() {
        return userType;
    }
    public void setUserType(String userType) {
        this.userType = userType;
    }
    public String getIsActive() {
        return isActive;
    }
    public void setIsActive(String isActive) {
        this.isActive = isActive;
    }
}

测试类:HandlerUtil

import java.io.IOException;
import java.io.InputStream;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.mcmcg.ams.lambda.model.UserDetails;

public class HandlerUtil {
    private static final Logger LOG = LogManager.getLogger(HandlerUtil.class);

    private HandlerUtil() {
    }

    public static void main(String[] args) {
        try (InputStream instream = HandlerUtil.class.getClassLoader().getResourceAsStream("data.json")) {
            UserDetails sample = new ObjectMapper().readValue(instream, UsersList.class);
            System.out.println(sample.toString());
        } catch (IOException ex) {
            LOG.error("Exception occurred while laoding data.json file : ", ex);
        }
    }
}

异常: com.fasterxml.jackson.databind.JsonMappingException:由于输入结束,没有要映射的内容

您可以使用 jackson 的 ObjectMapper.readValue() 方法。

我认为您的解决方案将是这样的:

    String jsonBody = yourJson;
    ObjectMapper objectMapper = new ObjectMapper();
    try {
        UserDetailsMapDao userDetailsMapDao = objectMapper
                .readValue(jsonBody, UserDetailsMapDao.class);
    } catch (JsonParseException e) {
        // TODO Exception Handling
    } catch (JsonMappingException e) {
        // TODO Exception Handling
    } catch (IOException e) {
        // TODO Exception Handling
    }

你的道将是这样的:

公共类 UserDetailsMapDao {

private Map<String, UserDetails> userDetailsMap;

public String getUserDetailsMap() {
return userDetailsMap;
}
public void setUserDetailsMap(String userDetailsMap) {
this.userDetailsMap = userDetailsMap;
}

}

公共类用户详细信息{

private String userId;
private String location;
private String userType;
private String isActive;

public String getUserId() {
    return userId;
}
public void setUserId(String userId) {
    this.userId = userId;
}
public String getLocation() {
    return location;
}
public void setLocation(String location) {
    this.location = location;
}
public String getUserType() {
    return userType;
}
public void setUserType(String userType) {
    this.userType = userType;
}
public String getIsActive() {
    return isActive;
}
public void setIsActive(String isActive) {
    this.isActive = isActive;
}

}

JSON 的格式为Map<String, UserDetails>看一看,键0具有用户"Shailesh@gmail.com" ,键1具有"Vikram@gmail.com"

TypeReference<HashMap<String,UserDetails>> typeRef 
        = new TypeReference<HashMap<String,UserDetails>>() {};

HashMap<String,UserDetails> sample = new ObjectMapper()
                                  .readValue(instream, typeRef);

如果使用杰克逊使用@JsonAnySetter

public class UsersList {

private Map<String, UserDetails> users = new HashMap<>();

@JsonAnySetter
public void setUsers(String name, UserDetails value) {
this.addressDetails.put(name, value);
    }

 }

然后将其映射到UserDetails

 UserDetails sample = new ObjectMapper().readValue(instream, UsersList.class);

首先,在将 json 字符串反序列化为 DTO 之前,DTO 应包含无参数构造函数、getter 和 setter。 您当前的 DTO 将匹配如下所示的字符串。

{
    "users": [
        {
            "location": "6",
            "userType": "1",
            "isActive": "1",
            "userId": "Shailesh@gmail.com"
        },
        {
            "location": "7",
            "userType": "2",
            "isActive": "1",
            "userId": "Vikram@gmail.com"
        }
    ]
}

与上面提供的字符串示例匹配的 DTO 如下所示。

public class UsersList {
    UserDetails zero;
    UserDetails one;

    public UsersList() {
    }

    public UserDetails getZero() {
        return zero;
    }

    public void setZero(final UserDetails zero) {
        this.zero = zero;
    }

    public UserDetails getOne() {
        return one;
    }

    public void setOne(final UserDetails one) {
        this.one = one;
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM