json转换成java对象示例
json字符串转Java对象有很多工具可以使用,下面的小例子只是我练手的
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.jfinal.kit.JsonKit;
public class JsonToJavaObject {
public static void main(String[] args) {
Object o1 = parse("{\"aa\":123,cc:[1,2,3,4,{cd:f,bb:234}]}");
System.out.println(JsonKit.toJson(o1));
}
public static Object parse(String json){
if(json == null){
return null;
}
json = json.trim();
if("string".equals(typeof(json))){
return json;
}
if("map".equals(typeof(json))){
return parseMap(json);
}
if("list".equals(typeof(json))){
return parseList(json);
}
return null;
}
public static Map parseMap(String json){
if(!"map".equals(typeof(json))){
throw new RuntimeException("json 不是Map类型");
}
Map r = new HashMap();
parseToken(r,json,null);
return r;
}
public static List parseList(String json){
if(!"list".equals(typeof(json))){
throw new RuntimeException("json 不是list类型");
}
List r = new ArrayList();
parseToken(null, json, r);
return r;
}
public static String typeof(String json){
if(json.length() == 0)return "string";
if('{'==json.charAt(0)){
if('}' == json.charAt(json.length()-1)){
return "map";
}
}
if('['==json.charAt(0)){
if(']'==json.charAt(json.length()-1)){
return "list";
}
}
return "string";
}
private static void parseToken(Map r, String json,List r2) {
boolean syh = true; //双引号
boolean dyh = true;//单引号
boolean dkh = true;//大括号
boolean zkh = true;//中括号
boolean isKey = true;
StringBuffer key = new StringBuffer();
StringBuffer value = new StringBuffer();
for(int i=1;i<json.length()-1;i++){
char item = json.charAt(i);
if(dyh&&syh&&zkh)if('{' == item || '}' == item){
dkh = !dkh;
}
if(dyh&&syh&&dkh)if('[' == item || ']' == item){
zkh = !zkh;
}
if(dyh&&dkh&&zkh)if('"' == item){
syh = !syh;
continue;
}
if(syh&&dkh&&zkh)if(syh)if('\'' == item){
dyh = !dyh;
continue;
}
if(dyh&&syh&&dkh&&zkh)if(r2==null)if(dyh)if(':'==item){
isKey = false;
continue;
}
if(dyh&&syh&&dkh&&zkh)if(','==item){
isKey = true;
if(r != null){
r.put(key.toString(), parse(value.toString()));
}
if(r2 != null){
r2.add(parse(key.toString()));
}
key = new StringBuffer();
value = new StringBuffer();
continue;
}
if(isKey){
key.append(item);
}else{
value.append(item);
}
}
if(!key.toString().trim().equals("")){
if(r != null){
if(value.toString().trim().equals(""))throw new RuntimeException("json 格式错误");
r.put(key.toString(), parse(value.toString()));
}
if(r2 != null){
r2.add(parse(key.toString()));
}
}
}
}
{"aa":"123","cc":["1","2","3","4",{"bb":"234","cd":"f"}]}