从数据库中获取数据后,我必须返回一个JSON格式的对象。 示例数据库如下:
我希望JSON返回值为:
{
"Name": "Mark",
"Address": {
"Adr1": "123 Avenue",
"Adr2": "Apt-121",
"City": "Phoenix",
"State": "AZ"
}
}
到目前为止,我已经能够将整个地址文本作为字符串获取,这对我没用。它看起来像这样:
{
"Name": "Mark",
"Address": "{Adr1:123 Avenue, Adr2:Apt-121, City:Phoenix, State:AZ}"
}
我的POJO看起来像:
class Profile{
String name;
Address addr;
}
class Address{
String Adr1;
String Adr2;
String City;
String State;
}
我尝试为地址创建一个单独的类,但我无法映射地址(Adr1,Adr2,City,State)的各个参数,以便创建我需要的JSON对象。
任何人都可以帮我将数据库中的正确数据映射到JSON吗?
答案 0 :(得分:1)
我建议您将第二列解析为地址对象,然后使用Name创建一个配置文件对象,即COl#1和从Col#2创建的Address对象
String name = "Mark";
String addressDetail = "{Adr1:123 Avenue, Adr2:Apt-121, City:Phoenix, State:AZ}";
addressDetail = addressDetail.replace('{',' ');
addressDetail = addressDetail.replace('{',' ');
String[] addressDetailElems = addressDetail.split(",");
for(String elem : addressDetailElems) {
System.out.println(elem);
String[] valX = addressDetail.split(":");
System.out.println(valX[0] + " -- " + valX[1]);
}
我以为我能够进行json解析,但显然我失败了。因为没有引用值
如果文本可能是这样的话,那么json Parsing会起作用String addressDetail = "{\"Adr1\":\"123 Avenue\", \"Adr2\":\"Apt-121\", \"City\":\"Phoenix\", \"State\":\"AZ\"}";
Gson gson = new Gson();
Address addressObj = gson.fromJson(addressDetail, Address.class);//new TypeToken<List<Address>>() {}.getType());
System.out.println(addressObj);
答案 1 :(得分:1)
如果你遇到那种格式,你肯定需要处理解析字符串。我过去曾经使用过杰克逊非常好的经历。我不确定它是否会比另一个更好地处理你的字符串,但可能值得一看。我会尝试至少在格式化中获取JSON字符串,以便正确引用其值。这就是战争中你应该能够获胜的战斗!
要在更好的格式化字符串中处理字符串,我建议使用结果处理程序映射到您的类。这将帮助您至少隔离行为,并更好地能够对您的期望进行单元测试。在其中,您可以处理解析地址数据并将所有内容映射到与您想要的格式匹配的对象列表。
一个例子:
//model for using with mapper
public class DatabaseProfile {
String name;
String address;
}
//converts database profile to Profile
public class ProfileResultHandler implements ResultHandler {
private List<AdStrategyTargetDTO> profiles = new ArrayList<>();
public List<Profile> getProfiles() { return profiles; }
@Override public void handleResult(ResultContext context) {
DatabaseProfile databaseProfile = (DatabaseProfile)context.getResultObject();
Address address = getAddress(databaseProfile.getAddress());
Profile profile = new Profile(databaseProfile.getName(),address);
profiles.add(profile);
}
private Address getAddress(String addressString){
Address address = new Address();
//do you string parsing here and fill in address object
//hopefully just using some deserializer but if all else fails
//this is where you would manually parse the string, I'll leave that
//detail up to you
return address;
}
}
然后将其与mapper一起使用可能类似于以下内容
public List<Profile> getProfilesFromDatabase(){
//the result handle just becomes a parameter of the interfaced call
ProfileResultHandler resultHandler = new ProfileResultHandler
profileMapper.getProfiles(resultHandler);
return resultHandler.getProfiles();
}