json字符串,JSONObject对象,JavaBean对象互转。

json字符串,JSONObject对象,JavaBean对象互转。包名 importnet sf json JSONObject 1 maven 地址 dependency groupId net sf json lib groupId artifactId json lib artifactId version 2 4 version dependency

包名:import net.sf.json.JSONObject;

1.maven地址

 
   
   
     net.sf.json-lib 
    
   
     json-lib 
    
   
     2.4 
    
   
     jdk15 
    
  

2.People对象详情如下:

package pojo; public class People { private int id; private int age; private String name; public People(int id, int age, String name) { super(); this.id = id; this.age = age; this.name = name; } public People() { super(); } public int getId() { return id; } public void setId(int id) { this.id = id; } public int getAge() { return age; } public String getName() { return name; } public void setAge(int age) { this.age = age; } public void setName(String name) { this.name = name; } @Override public String toString() { return "People [id=" + id + ", age=" + age + ", name=" + name + "]"; } }

 3.json字符串转为JSONObject对象:

String jsonStr = "{\"name\":\"1\",\"age\":1,\"id\":0}"; // json字符串转为JSONObject 对象 JSONObject jsonObject = JSONObject.fromObject(jsonStr); System.out.println("name:" + jsonObject.get("name")); System.out.println("age:" + jsonObject.get("age")); System.out.println("id:" + jsonObject.get("id"));

4.JSONObject转为json字符串:

// JSONObject转为json字符串 String string = jsonObject.toString(); System.out.println("string" + string);

 

 

5.JSONObject对象转化为javaBean对象:

// JSONObject转为javaBean People people = (People)JSONObject.toBean(jsonObject, People.class); System.out.println(people);

6.有时候,我们需要将一个集合json转化为一个java的List

集合:

例如如下的一个json字符串:

[{"age":1,"id":1,"name":"first"}, {"age":2,"id":2,"name":"second"}, {"age":3,"id":3,"name":"third"}]

这个json字符串中包含的数据可以转化为一个List 集合,代码如下:

// 将List的Json字符串转化为List 
  
    集合 String listStr = "[{\"age\":1,\"id\":1,\"name\":\"first\"},{\"age\":2,\"id\":2,\"name\":\"second\"},{\"age\":3,\"id\":3,\"name\":\"third\"}]"; JSONArray jsonArray2 = JSONArray.fromObject(listStr); List 
   
     peopleList2 = (List 
    
      )JSONArray.toCollection(jsonArray2, People.class); for(People peo : peopleList2) { System.out.println(peo); } 
     
    
  

7.JSONArray的遍历:

List 
  
    peopleList = new ArrayList 
   
     (); peopleList.add(new People(1,1,"first")); peopleList.add(new People(2,2,"second")); peopleList.add(new People(3,3,"third")); JSONArray jsonArray = JSONArray.fromObject(peopleList); // JSONArray的遍历 for (int i = 0; i < jsonArray.size(); i++) { JSONObject jsonObject2 = jsonArray.getJSONObject(i); People people1 = (People)jsonObject.toBean(jsonObject2, People.class); System.out.println(people1); } 
    
  

 

 

 

 

 

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/224701.html原文链接:https://javaforall.net

(0)
上一篇 2026年3月17日 上午11:20
下一篇 2026年3月17日 上午11:20


相关推荐

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号