您的位置:首页 > 编程语言 > Java开发

JAVA操作JSON格式数据

2015-01-27 18:29 513 查看
由于近些日子公司在弄微信项目,而微信官方API所提供的接口当中,有些需要以POST方式进行请求,且数据传输格式要求为JSON格式数据,之前没怎么研究过,而且传递的数据格式相对也比较简单,所以直接都是采用的字符串拼接的方式进行组装的,之后再用String.format格式化一下就好了。

//需要提交的json数据
String jsonData = "{\"openid\":\"%s\",\"to_groupid\":%d}";
//调用接口移动用户分组
JSONObject jsonObject = WeixinUtil.httpRequest(requestUrl, "POST", String.format(jsonData, openId,groupId));


但是,今天用到消息模板接口的时候,发现POST请求的数据有点多,如果还是用这种方式就显得有些麻烦了,而且也不是很直观,需要对双引号做转义操作,有的时候转多了看着就头晕。所以特定查了一翻资料自己研究了一下。

首先,因为要用到json,所以项目中先要导入json开发工具包,用于Java对象和Json字符串之间的转换;

json开发工具包一共有3个jar:ezmorph-1.0.6.jar,json-lib-2.2.3-jdk13.jar和morph-1.1.1.jar。

这三个jar工具包已经上传至CSDN。有需要的话可以去下载:

http://download.csdn.net/detail/hu1991die/8401677

示例代码:

package com.json;

import java.util.Iterator;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/**
* Java操作JSON格式数据
* @author feizi
* @time 2015-1-27下午5:36:13
*/
public class TestJSON {

public static void main(String[] args) {
//jsonObject:{"right":"right","left":"left","obj":{"second":"222","third":"333"},"ele":{"four":"444","five":"555"},"data":[{"name":"张三","age":"23","sex":"男"},{"name":"李三","age":"20","sex":"女"}]}
JSONObject jsonObject = TestJSON.createJSONObject();
// 输出jsonobject对象
System.out.println("jsonObject:" + jsonObject);

// 根据key返回一个字符串
String right = jsonObject.getString("right");
System.out.println("right==>" + right); //right==>right

JSONObject obj = (JSONObject) jsonObject.get("obj");
System.out.println("obj==>"+obj);//obj==>{"second":"222","third":"333"}

String second = (obj == null ? "" : (String)obj.get("second"));
System.out.println("second==>" + second); //second==>222

JSONArray array = jsonObject.getJSONArray("data");
System.out.println("array==>"+array);//array==>[{"name":"张三","age":"23","sex":"男"},{"name":"李三","age":"20","sex":"女"}]

if(!array.isEmpty()){
for(int i = 0; i < array.size(); i++){
//{"name":"张三","age":"23","sex":"男"}
//{"name":"李三","age":"20","sex":"女"}
JSONObject element = (JSONObject) array.get(i);//array.get(i)方法默认返回的是Object类型,需要造型成JSONObject类型才能取出key值
System.out.println("element==>"+element);

String name = (String)element.get("name");
String age = (String)element.get("age");
String sex = (String)element.get("sex");

//name==>张三
//age==>23
//sex==>男
//name==>李三
//age==>20
//sex==>女
System.out.println("name==>"+name);
System.out.println("age==>"+age);
System.out.println("sex==>"+sex);
}

//或者用iterator迭代器进行迭代
for (Iterator<Object> iterator = array.iterator(); iterator.hasNext();) {
JSONObject element = (JSONObject) iterator.next();
System.out.println("element==>"+element);
//之后和上面一样
}

}
}

public static JSONObject createJSONObject(){
JSONObject jsonObject = new JSONObject();

//一般格式
//jsonObject:{"right":"right","left":"left"}
jsonObject.put("right", "right");
jsonObject.put("left", "left");

//嵌套格式
//jsonObject:{"obj":{"second":"222","third":"333"},"ele":{"four":"444","five":"555"}}
JSONObject jsonObj = new JSONObject();
jsonObj.put("second", "222");
jsonObj.put("third", "333");

JSONObject ele = new JSONObject();
ele.put("four", "444");
ele.put("five", "555");

jsonObject.element("obj", jsonObj);
jsonObject.element("ele", ele);

//数组嵌套格式
//jsonObject:{"data":[{"name":"张三","age":"23","sex":"男"},{"name":"李三","age":"20","sex":"女"}]}
JSONObject dataEle1 = new JSONObject();
dataEle1.put("name", "张三");
dataEle1.put("age", "23");
dataEle1.put("sex", "男");

JSONObject dataEle2=new JSONObject();
dataEle2.put("name", "李三");
dataEle2.put("age", "20");
dataEle2.put("sex", "女");

JSONArray jsonArray = new JSONArray();
jsonArray.add(0, dataEle1);
jsonArray.add(1, dataEle2);

jsonObject.accumulate("data", jsonArray);
//jsonObject.element("data", jsonArray);//貌似这两种方法都可以,我没有去详细的查过,所以也不清楚它们两者之间到底有什么区别
return jsonObject;
}

}


关于微信API中的模板消息接口:

POST数据说明

POST数据示例如下:

{
"touser":"OPENID",
"template_id":"ngqIpbwh8bUfcSsECmogfXcV14J0tQlEpBO27izEYtY",
"url":"http://weixin.qq.com/download",
"topcolor":"#FF0000",
"data":{
"first": {
"value":"恭喜你购买成功!",
"color":"#173177"
},
"keynote1":{
"value":"巧克力",
"color":"#173177"
},
"keynote2": {
"value":"39.8元",
"color":"#173177"
},
"keynote3": {
"value":"2014年9月16日",
"color":"#173177"
},
"remark":{
"value":"欢迎再次购买!",
"color":"#173177"
}
}
}


Java中进行封装,组装成上面的JSON格式数据

我的方法比较笨,仅作参考:

public class JsonTemplate {
private String touser;//接收者
private String template_id;//模板ID
private String url;//URL地址
private String topcolor;//顶部颜色
private JSONObject data;//内容

public JsonTemplate(){

}

public String getTouser() {
return touser;
}

public void setTouser(String touser) {
this.touser = touser;
}

public String getTemplate_id() {
return template_id;
}

public void setTemplate_id(String template_id) {
this.template_id = template_id;
}

public String getUrl() {
return url;
}

public void setUrl(String url) {
this.url = url;
}

public String getTopcolor() {
return topcolor;
}

public void setTopcolor(String topcolor) {
this.topcolor = topcolor;
}

public JSONObject getData() {
return data;
}

public void setData(JSONObject data) {
this.data = data;
}
}


package com.wx.pojo.template;
/**
* 模板消息的内容
* @author feizi
* @time 2015-1-27下午2:53:49
*/
public class DataElement {
private String title;// 标题名
private String value;// 内容
private String color;// 颜色

public DataElement() {

}

public DataElement(String title, String value, String color) {
this.title = title;
this.value = value;
this.color = color;
}

public String getTitle() {
return title;
}

public void setTitle(String title) {
this.title = title;
}

public String getValue() {
return value;
}

public void setValue(String value) {
this.value = value;
}

public String getColor() {
return color;
}

public void setColor(String color) {
this.color = color;
}
}


测试上面的JSON示例:

/**
* 组装JSON格式
* @param tmp
* @param dataList
* @return
*/
public static JSONObject createJSONObject(JsonTemplate tmplate,List<DataElement> dataList){
JSONObject dataJson = new JSONObject();
if(dataList != null && dataList.size() > 0){
JSONObject elementJson = null;
for (DataElement data : dataList) {
elementJson = new JSONObject();
elementJson.put("value", data.getValue());
elementJson.put("color", data.getColor());

dataJson.put(data.getTitle(), elementJson);
}
}

JSONObject tmpJSON = new JSONObject();
tmpJSON.put("touser", tmplate.getTouser());
tmpJSON.put("template_id", tmplate.getTemplate_id());
tmpJSON.put("url", tmplate.getUrl());
tmpJSON.put("topcolor", tmplate.getTopcolor());
tmpJSON.put("data", dataJson);

return tmpJSON;
}

public static void main(String[] args) {
JsonTemplate tmp = new JsonTemplate();
tmp.setTouser("OPENID");
tmp.setTemplate_id("ngqIpbwh8bUfcSsECmogfXcV14J0tQlEpBO27izEYtY");
tmp.setUrl("http://weixin.qq.com/download");
tmp.setTopcolor("#FFF");

DataElement data0 = new DataElement();//由于已经重写了带参构造器,也可以直接调用带参构造器进行初始化操作
data0.setTitle("first");
data0.setValue("恭喜你购买成功!");
data0.setColor("#173177");

DataElement data1 = new DataElement();
data1.setTitle("keynote1");
data1.setValue("巧克力");
data1.setColor("#173177");

DataElement data2 = new DataElement();
data2.setTitle("keynote2");
data2.setValue("39.8元");
data2.setColor("#173177");

DataElement data3 = new DataElement();
data3.setTitle("keynote3");
data3.setValue("2014年9月16日");
data3.setColor("#173177");

DataElement data4 = new DataElement();
data4.setTitle("remark");
data4.setValue("欢迎再次购买!");
data4.setColor("#173177");

List<DataElement> dataList = new ArrayList<DataElement>();
dataList.add(data0);
dataList.add(data1);
dataList.add(data2);
dataList.add(data3);
dataList.add(data4);

JSONObject tmpJSON = JsonTemplate.createJSONObject(tmp, dataList);

System.out.println(tmpJSON);

}


运行之后,控制台的输出结果:

{"touser":"OPENID","template_id":"ngqIpbwh8bUfcSsECmogfXcV14J0tQlEpBO27izEYtY","url":"http://weixin.qq.com/download","topcolor":"#FFF","data":{"first":{"value":"恭喜你购买成功!","color":"#173177"},"keynote1":{"value":"巧克力","color":"#173177"},"keynote2":{"value":"39.8元","color":"#173177"},"keynote3":{"value":"2014年9月16日","color":"#173177"},"remark":{"value":"欢迎再次购买!","color":"#173177"}}}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: