您当前的位置: 首页 >  json

梁云亮

暂无认证

  • 2浏览

    0关注

    1211博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

使用json-lib 和 org.json处理JSON数据

梁云亮 发布时间:2019-10-16 16:42:21 ,浏览量:2

Json 数据处理技术 之 json-lib 和 org.json 1、json-lib 示例1:将字符串转换成JSON对象并解析
  • 工具类:
public class ParseUtil {
	public static void String2JSON(String str) {
		try {
			JSONObject obj = new JSONObject(str);
			JSONArray array = obj.getJSONArray("stus");
			JSONObject object = array.getJSONObject(1);
			String name = object.getString("name");
			int age = object.getInt("age");
			System.out.println(name + " : " + age);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
  • 测试类:
    public static void main(String[] args) throws IOException {
        String data = "{stus:[ {'name':'zhangsan','age':23,'score':[88,77,66]}, {'name':'lisi','age':22,'score':[44,55,33]}],'status':'OK' }";
        ParseUtil.String2JSON(data);
    }
示例2:List对象转换成数组形式的JSON数据
  • 创建实体类Stu,为其提供id、name、age三个属性。
  • 转换代码:
private JSONArray list2json(List list) {
	JSONArray array = new JSONArray();
	for (Stu stu : list) {
		JSONObject object = new JSONObject();
		try {
			object.put("id", stu.getId());
			object.put("name", stu.getName());
			object.put("age", stu.getAge());
			array.put(object);
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}
	return jsonArray;
}
  • 测试代码:
public void test() {
		ArrayList list = new ArrayList();
		list.add(new Stu(1,"zhangsan",23));
		list.add(new Stu(2,"lisi",22));
		list.add(new Stu(3,"wanger",23));
		JSONArray jsonArray = list2json(list);
		System.out.println(jsonArray.toString());
}
org.json 示例1:JSONObject
@Test
public void fun1() throws JSONException {
	JSONObject json = new 
				JSONObject("{'id':1001,'name':'zhangsan','birth':'1999-9-9'}");
	int id = json.getInt("id");
	String name = json.getString("name");
	String birth = json.getString("birth");
	System.out.println(id + "  " + name + "  " + birth);
}
示例2:JSONArray
@Test
public void fun2() throws JSONException {
	JSONArray json = new JSONArray(
				"[{'id':1001,'name':'zhangsan'},{'id':1002,'name':'lisi'},1234]");
	System.out.println(json.getString(0));
	System.out.println(json.getJSONObject(1).getString("name"));
	System.out.println(json.getInt(2));
}

JSONStringer是一个用于快速构造JSON文本的工具,它提供了如下重要方法:

  • bject():开始一个对象,即添加{;
  • enObject():结束一个对象,即添加}
  • array():开始一个数组,即添加[;
  • endArray():结束一个数组,即添加]
  • key():表示添加一个key;
  • value():表示添加一个value
示例3:JSONStringer
@Test
public void fun4() throws JSONException {
	JSONObject obj1 = new JSONObject();
	obj1.put("id", 1001).put("name", "zhangsan");
	JSONObject obj2 = new JSONObject();
	obj2.put("id", 1002).put("name", "lisi");
	JSONStringer stringer = new JSONStringer();
	stringer.array().value(obj1).value(obj2).endArray();
	System.out.println(stringer);
}
关注
打赏
1665409997
查看更多评论
立即登录/注册

微信扫码登录

0.0448s