介绍
这篇文章主要介绍了使用Java怎么将Json字符串与对象对象进行转换,小编觉得不错,现在分享给大家,也给大家做个参考,一起跟随小编来看看吧!
public class User { private 才能;String 名称; private 才能;Integer 年龄; private 才能;String 位置; public 才能;用户(),{ ,,} public 才能;用户(String 名称),{ ,,,this.name =,名称; ,,} public 才能;用户(名称、String Integer 年龄),{ ,,,this.name =,名称; ,,,this.age =,年龄; ,,} public 才能;用户(名称、String Integer 年龄,String 位置),{ ,,,this.name =,名称; ,,,this.age =,年龄; ,,,this.location =,位置; ,,} public 才能;String  getName (), { ,,,return 名称; ,,} public 才能;void  setName (String 名称),{ ,,,this.name =,名称; ,,} public 才能;Integer  getAge (), { ,,,return 年龄; ,,} public 才能;void  setAge (Integer 年龄),{ ,,,this.age =,年龄; ,,} public 才能;String  getLocation (), { ,,,return 位置; ,,} setLocation public 才能;void (String 位置),{ ,,,this.location =,位置; ,,} @Override才能 public 才能;String  toString (), { ,,,return “用户{“+ ,,,,,,,“name=& # 39;“, +, name +, & # 39; \ & # 39; & # 39; + ,,,,,,,,,,岁=?+,age + ,,,,,,,,,,位置=& # 39;“,+,位置+,& # 39;\ & # 39;& # 39;+ ,,,,,,,& # 39;}& # 39;; ,,} }
<强> 1,Json-Lib 强>
maven依赖如下,需注意& lt; classifier> jdk15 jar包区分jdk1.3和jdk1.5版本
,, & lt; dependency> ,,& lt; groupId> net.sf.json-lib ,,& lt; artifactId> json-lib ,,& lt; version> 2.4 & lt;/version> ,,& lt; classifier> jdk15 & lt;才能/dependency>
测试演示
import net.sf.json.JSONObject; public class  JsonLibDemo { public 才能;static  void main (String [], args), { ,,,//创建测试对象 ,,,User User =, new 用户(“李宁“,24日,“北京“); ,,,System.out.println(用户); ,,,//转成json字符串 ,,,JSONObject JSONObject =, JSONObject.fromObject(用户); ,,,String json =, jsonObject.toString (); ,,,System.out.println (json); ,,,//json字符串转成对象 ,,,JSONObject jsonObject1 =, JSONObject.fromObject (json); ,,,User user1 =,(用户),JSONObject.toBean (jsonObject1 User.class); ,,,System.out.println (user1); ,,} }
<强> 2,org。json 强>
maven依赖如下
,, & lt; dependency> ,,& lt; groupId> org.json ,,& lt; artifactId> json ,,& lt; version> 20170516 & lt;/version> & lt;才能/dependency>
测试演示
import org.json.JSONObject; public class  OrgJsonDemo { public 才能;static  void main (String [], args), { ,,,//创建测试对象 ,,,User User =, new 用户(“李宁“,24日,“北京“); ,,,System.out.println(用户); ,,,//转成json字符串 ,,,String json =, new JSONObject(用户).toString (); ,,,System.out.println (json); ,,,//json字符串转成对象 ,,,JSONObject JSONObject =, new JSONObject (json); ,,,String name =, jsonObject.getString (“name"); ,,,Integer age =, jsonObject.getInt (“age"); ,,,String 位置=,jsonObject.getString (“location"); ,,,User user1 =, new 用户(姓名、年龄、位置); ,,,System.out.println (user1); null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null使用Java怎么将Json字符串与对象对象进行转换