我需要将以下java类转换为具有不同属性名称的json字符串:
public class Company {
private String companyYCode;
private String companyName;
getxx and setxx
}
我需要这个作为json字符串
{" y-code":" CICPK1214131231"," company_name":"某些公司" }
答案 0 :(得分:1)
是的,我认为你的简单方法是使用Jackson库来自定义json属性。 如果使用maven,则可以在pom.xml中添加依赖项:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>
在你的模型类中,只需使用注释JsonProperty来配置你想要的值:
public class Company {
@JsonProperty ("y-code")
private String companyYCode;
@JsonProperty ("company_name")
private String companyName;
}
这样,当您将对象公司解析为Json时,您的json字符串将具有您想要的属性:
{&#34; y-code&#34;:&#34; CICPK1214131231&#34;,&#34; company_name&#34;:&#34;某些公司&#34; }
答案 1 :(得分:0)
你可以写一个方法
public String toJson() {
JSONObjectBuilder json = new JSONObjectBuilder();
/*
add 'whatever you like - content' here
*/
return json.toString();
}
答案 2 :(得分:0)
使用杰克逊图书馆......
public class Company {
@JsonProperty ("y-code")
private String companyYCode;
@JsonProperty ("company_name")
private String companyName;
getxx and setxx
}
答案 3 :(得分:0)
主要班级......
import java.io.File;
import java.io.IOException;
import org.elasticsearch.common.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class ObjToJson {
public static void main(String[] args) {
Company user = new Company();
ObjectMapper mapper = new ObjectMapper();
try {
mapper.writeValue(new File("c:\\user.json"), user);
System.out.println(mapper.writeValueAsString(user));
} catch (JsonGenerationException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
POJO:
public class Company {
private String companyYCode="CICPK1214131231";
private String companyName="Some company";
@Override
public String toString() {
return "User [companyYCode=" + companyYCode + ", companyName=" + companyName + "]";
}
public String getCompanyYCode() {
return companyYCode;
}
public void setCompanyYCode(String companyYCode) {
this.companyYCode = companyYCode;
}
public String getCompanyName() {
return companyName;
}
public void setCompanyName(String companyName) {
this.companyName = companyName;
}
}