JSON,String和对象之间的转换

1.String转JSON

String jstr="{'json':'jsonvalue','bool':true,'int':1,'double':'20.5'}";
JSONObject json=JSONObject.fromObject(jstr);
boolean bool=json.getBoolean("bool");
int i=json.getInt("int");
double d=json.getDouble("double");
String value=json.getString("json");
System.out.println("bool="+String.valueOf(bool)+"\tjson="+value+"\tint="+i+"\tdouble="+d);

2.String转JSON再转对象

假如你是有一个bean对象 class User{ private String name; private String psw; //封装getter/setter省略 } String u="{'name':'sail331x','psw':'123456789'}"; User user=(User)JSONObject.toBean(JSONObject.fromObject(u),User.class); 就可以了。

3.对象转JSON再转String

把一个user变成json对象: JSONObject juser=JSONObject.fromObject(user); String jstr=juser.toString();//这个就变成json字符串了

你可能感兴趣的:(java)