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"}]}