Operate data in JSON format in JAVA

Source: Internet
Author: User
Tags getcolor openid

Operate data in JSON format in JAVA

 

In recent days, the company has been engaged in projects, and some of the interfaces provided by official APIs need to be requested in POST mode, and the data transmission format must be in JSON format, I have never studied it before, and the transmitted data format is relatively simple. Therefore, it is directly assembled by concatenating strings and then assembled with strings. format.

 

 

// Json data to be submitted String jsonData = {openid: % s, o_groupid: % d}; // call the interface to move the user group JSONObject jsonObject = WeixinUtil. httpRequest (requestUrl, POST, String. format (jsonData, openId, groupId ));

 

However, when we use the message template interface today, we find that there are a lot of data in POST requests. If we still use this method, it will be a little troublesome and not very intuitive, you need to escape double quotation marks. Sometimes, when you turn more, you will be dizzy. So I checked the information and studied it myself.

 

First, because json is required, the project must first import the json Development Kit for conversion between Java objects and Json strings;

The json Development Kit has a total of three jar: ezmorph-1.0.6.jar, json-lib-2.2.3-jdk13.jar and morph-1.1.1.jar.

These three jar packages have been uploaded to CSDN.

 

Sample Code:

 

Package com. json; import java. util. iterator; import net. sf. json. JSONArray; import net. sf. json. JSONObject;/*** Java operation JSON format data * @ author feizi * @ time 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: Zhang San, age: 23, sex: Male}, {name: Li San, age: 20, sex: Female}]} JSONObject jsonObject = Test JSON. createJSONObject (); // output the jsonobject System. out. println (jsonObject: + jsonObject); // returns a String right = jsonObject based on the key. 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: Zhang San, age: 23, sex: Male}, {name: Li San, age: 20, sex: Female}] if (! Array. isEmpty () {for (int I = 0; I <array. size (); I ++) {// {name: Zhang San, age: 23, sex: Male} // {name: Li San, age: 20, sex: female} JSONObject element = (JSONObject) array. get (I); // array. by default, the get (I) method returns the Object type. The key value System can be retrieved only when the JSONObject type is modeled. out. println (element ==>+ element); String name = (String) element. get (name); String age = (String) element. get (age); String sex = (String) element. get (sex ); // name => Zhang San // age => 23 // sex => male // name => Li San // age => 20 // sex => female System. out. println (name ==>+ name); System. out. println (age ==>+ age); System. out. println (sex ==>+ sex);} // or use the iterator Iterator to iterate for (iteratorIterator = array. iterator (); iterator. hasNext ();) {JSONObject element = (JSONObject) iterator. next (); System. out. println (element ==>+ element); // later, the same as above }} public static JSONObject createJSONObject () {JSONObject jsonObject = new JSONObject (); // normal format // jsonObject: {right: right, left: left} jsonObject. put (right, right); jsonObject. put (left, left); // nested format // 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); // array nested format // jsonObject: {data: [{name: James, age: 23, sex: Male}, {name: James, age: 20, sex: Female}]} JSONObject dataEle1 = new JSONObject (); dataEle1.put (name, Michael); dataEle1.put (age, 23); dataEle1.put (sex, male ); JSONObject dataEle2 = new JSONObject (); dataEle2.put (name, Li San); dataEle2.put (age, 20); dataEle2.put (sex, female); JSONArray jsonArray = new JSONArray (); jsonArray. add (0, dataEle1); jsonArray. add (1, dataEle2); jsonObject. accumulate (data, jsonArray); // jsonObject. element (data, jsonArray); // it seems that both methods can be used. I have not checked them in detail, so it is not clear what is the difference between the two? return jsonObject ;}}

About the template message interface in the API:

POST Data Description

An example of POST data is as follows:

 

 

{Touser: OPENID, template_id: ngqipbwh8bufcssecmogfxcv14j0tq1_bo27izeyty, url: http://weixin.qq.com/download, topcolor: # FF0000, data: {first: {value: Congratulations !, Color: #173177}, keynote1: {value: Chocolate, color: #173177}, keynote2: {value: 39.8 yuan, color: #173177}, keynote3: {value: September 16, 2014, color: #173177}, remark: {value: Welcome to purchase again !, Color: #173177 }}}

Encapsulated in Java and assembled into the above JSON format data

 

My method is stupid, just for reference:

 

Public class JsonTemplate {private String touser; // receiver private String template_id; // template IDprivate String url; // URL address private String topcolor; // The top color is private JSONObject data; // content 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;/*** template message content * @ author feizi * @ time 2:53:49 */public class DataElement {private String title; // title name private String value; // content private String color; // 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 ;}}

 

Test the preceding JSON example:

 

/*** Assemble JSON format ** @ param tmp * @ param dataList * @ return */public static JSONObject createJSONObject (JsonTemplate tmplate, List
 
  
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, tm Plate. 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 (ngqipbwh8bufcssecmogfxcv14j0tq1_bo27izeyty); tmp. setUrl (http://weixin.qq.com/download); tmp. setTopcolor (# FFF); DataElement data0 = new DataElement (); // you can directly call the with parameter constructor because the parameter constructor has been rewritten. Initialization operation data0.setTitle (first); data0.setValue (Congratulations! You purchased it !); Data0.setColor (#173177); DataElement data1 = new DataElement (); data1.setTitle (keynote1); data1.setValue (chocolate); data1.setColor (#173177); DataElement data2 = new DataElement (); data2.setTitle (keynote2); data2.setValue (39.8 RMB); data2.setColor (#173177); DataElement data3 = new DataElement (); data3.setTitle (keynote3); data3.setValue (September 16, 2014 ); data3.setColor (#173177); DataElement data4 = new DataElement (); data4.set Title (remark); data4.setValue (please purchase again !); Data4.setColor (#173177); List
  
   
DataList = new ArrayList
   
    
(); 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 );}
   
  
 

 

After running, the console outputs the following results:

 

{Touser: OPENID, template_id: ngqipbwh8bufcssecmogfxcv14j0tq1_bo27izeyty, url: Success !, Color: #173177}, keynote1: {value: Chocolate, color: #173177}, keynote2: {value: 39.8 yuan, color: #173177}, keynote3: {value: September 16, 2014, color: #173177}, remark: {value: Welcome to purchase again !, Color: #173177 }}}


 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.