Conversion between JSON and JAVA data

Source: Internet
Author: User
Tags tojson
Import net. sf. json. JSONArray;
Import net. sf. json. JSONException;
Import net. sf. json. JSONObject;
Import net. sf. json. JSONSerializer;


/**
* Converting a json object to a java object
*
* @ Throws JSONException
*/
@ Test
Public void jsonToJava (){
String json = "[{\" addTime \ ": \" 14:23:02 \ ", \" iccid \ ": \" 1111 \ ", \" id \ ": 0, \ "imei \": \ "2222 \", \ "imsi \": \ "3333 \", \ "phoneType \": \ "4444 \", \ "remark \": \ "aaaa \", \ "tel \" :\" 5555 \ "}]";
// Receives the {} object. An exception occurs when receiving the array object.
If (json. indexOf ("[")! =-1 ){
Json = json. replace ("[","");
}
If (json. indexOf ("]")! =-1 ){
Json = json. replace ("]", "");
}
JSONObject obj = new JSONObject (). fromObject (json );
SimInfo simInfo = (SimInfo) JSONObject. toBean (obj, SimInfo. class );
System. out. println ("obj:" + simInfo );
System. out. println (simInfo. getAddTime ());
System. out. println (simInfo. getIccid ());
System. out. println (simInfo. getImei ());
System. out. println (simInfo. getImsi ());
System. out. println (simInfo. getPhoneType ());
System. out. println (simInfo. getRemark ());
System. out. println (simInfo. getTel ());
System. out. println (simInfo. getId ());

DaoFactory. getSimInfoDao (). add (simInfo );
}

/**
* Convert json to a java Collection object
*/
@ Test
Public void jsonToJavas (){
String jsons = "[{\" addTime \ ": \" 14:23:02 \ ", \" iccid \ ": \" 1111 \ ", \" id \ ": 0, \ "imei \": \ "2222 \", \ "imsi \": \ "3333 \", \ "phoneType \": \ "4444 \", \ "remark \": \ "aaaa \", \ "tel \": \ "5555 \"}, "+
"{\" AddTime \ ": \" 2011-11-11 14:23:02 \ ", \" iccid \ ": \" 2222 \ ", \" id \ ": 0, \ "imei \": \ "2222 \", \ "imsi \": \ "3333 \", \ "phoneType \": \ "4444 \", \ "remark \": \ "aaaa \", \ "tel \" :\" 5555 \ "}]";
List <SimInfo> simInfos = getJavaCollection (new SimInfo (), jsons );
System. out. println (simInfos. size ());
For (SimInfo simInfo: simInfos ){
System. out. println ("addTime:" + simInfo. getAddTime ());
System. out. println ("========= ");
}

}

/**
* Encapsulate and convert a json object to a java Collection object
*
* @ Param <T>
* @ Param clazz
* @ Param jsons
* @ Return
*/
Private <T> List <T> getJavaCollection (T clazz, String jsons ){
List <T> objs = null;
JSONArray jsonArray = (JSONArray) JSONSerializer. toJSON (jsons );
If (jsonArray! = Null ){
Objs = new ArrayList <T> ();
List list = (List) JSONSerializer. toJava (jsonArray );
For (Object o: list ){
JSONObject jsonObject = JSONObject. fromObject (o );
T obj = (T) JSONObject. toBean (jsonObject, clazz. getClass ());
Objs. add (obj );
}
}
Return objs;
}

/**
* Converting a java object to a json object
*
* @ Throws JSONException
*/
@ Test
Public void javaToJson (){
SimInfo simInfo = new SimInfo ();
SimInfo. setAddTime (UtilTool. dateToStr (new Date (), null ));
SimInfo. setIccid ("1111 ");
SimInfo. setImei ("2222 ");
SimInfo. setImsi ("3333 ");
SimInfo. setPhoneType (4 );
SimInfo. setRemark ("aaaa ");
SimInfo. setTel ("5555 ");
// Convert a java object to a json object
String json = new JSONArray (). fromObject (simInfo). toString ();
// Json: [{"addTime": "14:23:02", "iccid": "1111", "id": 0, "imei": "2222 ", "imsi": "3333", "phoneType": "4444", "remark": "aaaa", "tel": "5555"}]
System. out. println ("json:" + json );
}

Jackson-core-asl-1.7.2.jar

Jackson-mapper-asl-1.7.2.jar

// Convert a Java object to JSON
StringWriter writer = new StringWriter ();
ObjectMapper mapper = new ObjectMapper ();
Mapper. writeValue (writer, simInfo );
String json = writer. toString ();

Json instance program based on json-lib.jar package
1. JSONObject to DynaBean
String json = "{name = \" json \ ", bool: true, int: 1, double: 2.2 }";
JSONObject jsonObject = JSONObject. fromObject (json );
// Abstract statement: DynaBean bean = (DynaBean) JSONSerializer. toJava (jsonObject );
Object bean = JSONObject. toBean (jsonObject );
// Object bean1 = JSONSerializer. toJava (jsonObject );
AssertEquals (jsonObject. get ("name"), PropertyUtils. getProperty (bean, "name "));
AssertEquals (jsonObject. get ("bool"), PropertyUtils. getProperty (bean, "bool "));
AssertEquals (jsonObject. get ("int"), PropertyUtils. getProperty (bean, "int "));
AssertEquals (jsonObject. get ("double"), PropertyUtils. getProperty (bean, "double "));

2. JSONObject to JavaBean
String json = "{name: \" zhangsan \ ", age: 25, hight: 1.72, sex: true }";
JSONObject jsonObject = JSONObject. fromObject (json );
UserBean bean = (UserBean) JSONObject. toBean (jsonObject, UserBean. class );
System. out. println (jsonObject );
Theoretically, this is fine, but there is an exception Caused by: java. lang. NoSuchMethodException: com. json. Json $ UserBean. <init> ()
             
3.JSONArray to List
String json = "[\"first\",\"second\"]";
JSONArray jsonArray = (JSONArray) JSONSerializer.toJSON(json);
List output = (List) JSONSerializer.toJava(jsonArray);

4.JSONArray to array
String json = "[\"first\",\"second\"]";
JSONArray jsonArray = (JSONArray) JSONSerializer.toJSON(json);
JsonConfig jsonConfig = new JsonConfig();
jsonConfig.setArrayMode(JsonConfig.MODE_OBJECT_ARRAY);
Object[] output = (Object[]) JSONSerializer.toJava(jsonArray, jsonConfig);
Object[] expected = new Object[] { "first", "second" };
ArrayAssertions.assertEquals(expected, output);

5. The JSON string is specially designed for JavaBean (the jar package required for demonstration by Liu huibin demo is included in the attachment)

String str = "[{\" id \ ": \" 328 \ ", \" mestype \ ": \" inbox \ "},{ \" id \": \ "327 \", \ "mestype \": \ "inbox \" },{ \ "id \": \ "279 \", \ "mestype \": \ "already \" },{ \ "id \": \ "278 \", \ "mestype \": \ "already \" },{ \ "id \": \ "277 \", \ "mestype \": \ "already \" },{ \ "id \": \ "310 \", \ "mestype \": \ "inbox \" },{ \ "id \": \ "308 \", \ "mestype \": \ "inbox \" },{ \ "id \": \ "305 \", \ "mestype \": \ "inbox \" },{ \ "id \": \ "304 \", \ "mestype \": \ "inbox \" },{ \ "id \": \ "303 \", \ "mestype \": \ "inbox \"}] ";
JSONArray jsonArray = (JSONArray) JSONSerializer. toJSON (str );
List list = (List) JSONSerializer. toJava (jsonArray );
For (Object obj: list ){
JSONObject jsonObject = JSONObject. fromObject (obj );
MessageBean bean = (MessageBean) JSONObject. toBean (jsonObject, MessageBean. class );
String id = bean. getId () + "";
String type = bean. getMestype ();
System. out. println (id + "" + type );
}
System. out. println (list. size ());

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.