1, Jackson Frame: This framework provides jsongenerator, objectmapper two classes provide a way to convert a Java object into a JSON object, JSON array format, or a JSON object, The array format is converted to a Java object.
2, Json-lib framework can also be used in JSON format and the conversion between Java objects, Json-lib provides the main classes are: Jsonobject, Jsonarray ....
3, show the use of two frameworks for mutual transformation:
First, Json-lib:package Com.inspur.json;
Import java.util.ArrayList;
Import java.util.List;
Import Net.sf.json.JSONArray;
Import Net.sf.json.JSONObject;
public class Jsontest {
public static void Main (string[] args) {
User U = new user ();
U.setname ("name1");
U.setage (1);
U.setphone ("123");
User U2 = new user ();
U2.setname ("name2");
U2.setage (2);
U2.setphone ("321");
List List = new ArrayList ();
List.add (U);
List.add (U2);
Creating Jsonobject Objects
Jsonobject JOBG = new Jsonobject ();
Creating Jsonobject Objects
Jsonarray arr = new Jsonarray ();
Convert an object to a JSON object's format
Jsonobject str = jobg.fromobject (u);
Format the list collection into a JSON array
Jsonarray str1 = arr.fromobject (list);
System.out.print (str);
System.out.print ("\ n");
System.out.print (STR1);
}
}
/* Run result * *
{"Age": 1, "name": "Name1", "Phone": "123"}
[{' Age ': 1, ' name ': ' name1 ', ' phone ': ' 123 '},{' age ': 2, ' name ': ' name2 ', ' phone ': ' 321 '}]
Two, the Jackson frame provides two class Jsongenerator Objectmapper
Package com.jackson.test;
Import java.util.ArrayList;
Import java.util.List;
Import org.codehaus.jackson.JsonEncoding;
Import Org.codehaus.jackson.JsonGenerator;
Import Org.codehaus.jackson.map.ObjectMapper;
public class Test {
public static void Main (string[] args) {
User U = new user ();
U.setname ("name1");
U.setage (1);
U.setsex ("man");
User U2 = new user ();
U2.setname ("name2");
U2.setage (2);
U2.setsex ("man");
List List = new ArrayList ();
List.add (U);
List.add (U2);
Objectmapper obj = new Objectmapper ();
Jsongenerator JG = null;
try {
JG = Obj.getjsonfactory (). Createjsongenerator (System.out,
JSONENCODING.UTF8);
System.out.println ("Jsongenerator");
WriteObject can convert Java objects, Eg:javabean/map/list/array, etc.
Jg.writeobject (U);
System.out.println ();
Jg.writeobject (list);
System.out.println ();
System.out.println ("Objectmapper");
WriteValue has the same functionality as WriteObject
Obj.writevalue (System.out, list);
catch (Exception e) {
E.printstacktrace ();
}
}
}
/* Operation Result * *
Jsongenerator
{' name ': ' name1 ', ' age ': 1, ' sex ': ' Man '}
[{' name ': ' name1 ', ' age ': 1, ' sex ': ' Man '},{' name ': ' name2 ', ' age ': 2, ' sex ': ' Man '}]
Objectmapper
[{' name ': ' name1 ', ' age ': 1, ' sex ': ' Man '},{' name ': ' name2 ', ' age ': 2, ' sex ': ' Man '}]
Jackson frame jar Package Download: http://download.csdn.net/detail/qh_java/7767473
JSON framework jar package Download: http://download.csdn.net/detail/qh_java/7767511