在Java Maven项目中,如何从JSON生成Java源文件?例如,我们有
{
"firstName": "John",
"lastName": "Smith",
"address": {
"streetAddress": "21 2nd Street",
"city": "New York"
}
}
当我们运行mvn generate-sources时,我们希望它生成这样的东西:
class Address {
JSONObject mInternalJSONObject;
Address (JSONObject json){
mInternalJSONObject = json;
}
String getStreetAddress () {
return mInternalJSONObject.getString("streetAddress");
}
String getCity (){
return mInternalJSONObject.getString("city");
}
}
class Person {
JSONObject mInternalJSONObject;
Person (JSONObject json){
mInternalJSONObject = json;
}
String getFirstName () {
return mInternalJSONObject.getString("firstName");
}
String getLastName (){
return mInternalJSONObject.getString("lastName");
}
Address getAddress (){
return Address(mInternalJSONObject.getString("address"));
}
}
作为Java开发人员,我需要在pom.xml中编写哪些XML行才能实现这一点?
试试我的解决方案
http://htmlpreview.github.io/?https://raw.githubusercontent.com/foobnix/android-universal-utils/master/json/generator.html
{
"auctionHouse": "sample string 1",
"bidDate": "2014-05-30T08:20:38.5426521-04:00 ",
"bidPrice": 3,
"bidPrice1": 3.1,
"isYear":true
}
结果Java类
private String auctionHouse;
private Date bidDate;
private int bidPrice;
private double bidPrice1;
private boolean isYear;
JSONObject get
auctionHouse = obj.getString("auctionHouse");
bidDate = obj.opt("bidDate");
bidPrice = obj.getInt("bidPrice");
bidPrice1 = obj.getDouble("bidPrice1");
isYear = obj.getBoolean("isYear");
JSONObject put
obj.put("auctionHouse",auctionHouse);
obj.put("bidDate",bidDate);
obj.put("bidPrice",bidPrice);
obj.put("bidPrice1",bidPrice1);
obj.put("isYear",isYear);
谢谢所有想帮忙的人。对我来说,这个脚本很有帮助。它只处理普通JSON,不关心类型,而是自动执行一些例程
String str =
"{"
+ "'title': 'Computing and Information systems',"
+ "'id' : 1,"
+ "'children' : 'true',"
+ "'groups' : [{"
+ "'title' : 'Level one CIS',"
+ "'id' : 2,"
+ "'children' : 'true',"
+ "'groups' : [{"
+ "'title' : 'Intro To Computing and Internet',"
+ "'id' : 3,"
+ "'children': 'false',"
+ "'groups':[]"
+ "}]"
+ "}]"
+ "}";
JSONObject json = new JSONObject(str);
Iterator<String> iterator = json.keys();
System.out.println("Fields:");
while (iterator.hasNext() ){
System.out.println(String.format("public String %s;", iterator.next()));
}
System.out.println("public void Parse (String str){");
System.out.println("JSONObject json = new JSONObject(str);");
iterator = json.keys();
while (iterator.hasNext() ){
String key = iterator.next();
System.out.println(String.format("this.%s = json.getString(\"%s\");",key,key ));
System.out.println("}");
如果你正在使用Jackson(那里最受欢迎的库),试试吧
https://github.com/astav/JsonToJava
它是开源的(最后更新于2013年6月7日至2021年),任何人都可以贡献。
总结
JsonToJava源类文件生成器,它根据提供的示例json数据推导模式并生成必要的java数据结构。
它鼓励团队在编写实际代码之前先用Json思考。
特性
可以为任意复杂的层次结构生成类(递归地)
是否可以读取现有的Java类,如果可以反序列化为这些结构,是否会这样做
当存在模棱两可的情况时,是否会提示用户输入