java json代码自动生成
package code;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.LineNumberReader;
import java.util.ArrayList;
import java.util.List;
public class Code {
private static List<String> readFile(String filename)
{
List<String> fileline = new ArrayList<String>();
try {
FileReader in = new FileReader(filename);
LineNumberReader reader = new LineNumberReader(in);
String s = reader.readLine();
while( s != null )
{
if(!s.startsWith("#"))
{
fileline.add(s);
}
s = reader.readLine();
}
reader.close();
in.close();
}catch(Exception e)
{
e.printStackTrace();
}
return fileline;
}
public static void genarateCode(List<String> line)
{
String cr="\r\n";
try{
FileWriter fw = new FileWriter("class.java");
for(int i = 0;i < line.size();i++)
{
String [] data = line.get(i).split(",");
if(data[1].trim().equalsIgnoreCase("int"))
{
fw.write("@SerializedName(\""+data[0]+"\")"+cr);
fw.write("private Integer "+toLowerCaseFirst(data[0])+";"+cr);
}
else if(data[1].trim().equalsIgnoreCase("string"))
{
fw.write("@SerializedName(\""+data[0]+"\")"+cr);
fw.write("private String "+toLowerCaseFirst(data[0])+";"+cr);
}
}
fw.write(cr);
fw.write(cr);
for(int i = 0;i < line.size();i++)
{
String [] data = line.get(i).split(",");
if(data[1].trim().equalsIgnoreCase("int"))
{
fw.write("public void set"+data[0]+"(Integer value)"+cr);
fw.write("{"+cr);
fw.write(" "+toLowerCaseFirst(data[0])+"="+"value;"+cr);
fw.write("}"+cr);
fw.write("public Integer get"+data[0]+"()"+cr);
fw.write("{"+cr);
fw.write(" return "+toLowerCaseFirst(data[0])+";"+cr);
fw.write("}"+cr);
}
else if(data[1].trim().equalsIgnoreCase("string"))
{
fw.write("public void set"+data[0]+"(String value)"+cr);
fw.write("{"+cr);
fw.write(" "+toLowerCaseFirst(data[0])+"="+"value;"+cr);
fw.write("}"+cr);
fw.write("public String get"+data[0]+"()"+cr);
fw.write("{"+cr);
fw.write(" return "+toLowerCaseFirst(data[0])+";"+cr);
fw.write("}"+cr);
}
}
fw.close();
}catch(Exception e)
{
}
}
public static String toLowerCaseFirst(String str)
{
StringBuilder sb = new StringBuilder(str);
sb.setCharAt(0, Character.toLowerCase(sb.charAt(0)));
str = sb.toString();
return str;
}
public static void main(String args[])
{
List<String> fileline = readFile("field.txt");
genarateCode(fileline);
System.out.println("success!");
}
}
field.txt
Name,String
Url,String
Duration,String
Desc,String
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。