net.sf.json包API部分功能解读

 1. Json字符串转化为JSONObject对象 :

String str = "{ \"user\": [\"c00296813\",\"x000001\"]}";
JSONObject jsonObject = JSONObject.fromObject(str);

2. JSONObject转化为json字符串:

String string = jsonObject.toString();

3. JSONObject.toBean(JSONObject , JSONConfig.class) 讲JSONObject转化为JavaBean :

package com.example.demo;

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 void setAge(int age) {this.age = age; }
    public String getName() {return name; }
    public void setName(String name) {this.name = name; }
    @Override
    public String toString() {
        return "people{" +
                "id=" + id +
                ", age=" + age +
                ", name='" + name + '\'' +
                '}';
    }
}

转化:

// JSONObject.toBean(jsonObject, JSONObject.class);
People people =(People)JSONObject.toBean(jsonObject, people.class);

4. 讲一个集合json转化为List<T>集合:

String jsonpeople = "[{"age":1,"id":1,"name":"first"},
                      {"age":2,"id":2,"name":"second"},
                      {"age":3,"id":3,"name":"third"}]" ;
//讲json字符串转化为List<T>集合
String jsonPeople ="[{\"age\":\"1\",\"id\":\"1\",\"name\":\"张三\"}," +
                "{\"age\":\"2\",\"id\":\"2\",\"name\":\"李四\"}," +
                "{\"age\":\"3\",\"id\":\"3\",\"name\":\"王五\"}]\n" ;
JSONArray jsonArray = JSONArray.fromObject(jsonPeople);
List<People> peopleList = (List<People>) JSONArray.toCollection(jsonArray,People.class);

5. JSONArray的遍历

for(int i= 0;i<jsonArray.size();i++){
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            People people = (People)JSONObject.toBean(jsonObject,People.class);
        }

 

 

 

 

 

 

 

 

 

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值