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

时间:2019-03-13 17:04:00

标签: java json jackson pojo

我正在尝试下面的代码,使用Jackson的ObjectMapper类将JSON以下的内容转换为POJO,但是会引发异常。谁能帮助我解决此问题。 JSON实际上是由UI提供的,因此无法更改其格式。我需要使用杰克逊库将此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:由于输入结束,没有内容要映射

3 个答案:

答案 0 :(得分:1)

您可以使用杰克逊的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
    }

您的Daos将是这样的:

公共类UserDetailsMapDao {

private Map<String, UserDetails> userDetailsMap;

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

}

公共类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;
}

}

答案 1 :(得分:0)

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);

答案 2 :(得分:0)

首先,在将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;
    }
}