2013年10月30日星期三

json format into javaBean object methods

A few days ago , when the interface Jingdong , Jingdong give me the returned results are returned in the form of json . The beginning of a headache , are accepted by str html page and then forwarded to break out directly addressed .
Then think about is not so resolved , this can only see the results , but can not handle the result set.
so you had to json format into javaBean can.
then looked at the statistics , the largest online information this way is the following :

String str = "[{\"id\":\"\",\"num\":\"\",\"dt\":\"2010-07-21T17:29:28\",\"consignee\":\"aaaa\",\"bank\":\"001\",\"ems\":\"0\"}]";
JSONArray array = JSONArray.fromObject(str);//先读取串数组
Object[] o = array.toArray();                //转成对像数组
System.err.println(o.length);            
JSONObject obj = JSONObject.fromObject(o[0]);//再使用JsonObject遍历一个个的对像
Order oo = (Order)obj.toBean(obj,Order.class);//指定转换的类型,但仍需要强制转化-成功
System.err.println(oo.getDt()+","+oo.getConsignee());

String ss = oo.getDt(); 

need jar package is : json-lib
But Jingdong provided inside a jar I did not find the required classes. ( Do not want to add additional jar package )
So keep looking , finally found a ObjectMapper
continue online search usage example of this class have , but relatively small, there is no direct can readily use.
So he began to try various ways to do their own examples .
end up spending two hours and finally try out a simple little example. And share with you , big hands who do not spray ! ~
First string:
String str="{\"student\":[{\"name\":\"leilei\",\"age\":23},{\"name\":\"leilei02\",\"age\":23}]}";

Next, create a class StudentList

public class StudentList {
List<Student> student;
public List<Student> getStudent() {
return student;
}

public void setStudent(List<Student> student) {
this.student = student;
}
}

Here is the Student class
public class Student {
private String name;
private int age;
//private StudentClass studentClass;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}

final test program

import java.util.List;
import org.codehaus.jackson.map.ObjectMapper;

public class JsonToJavaBean {
public static void main(String[] args) {
String str="{\"student\":[{\"name\":\"leilei\",\"age\":23},{\"name\":\"leilei02\",\"age\":23}]}";
Student stu = null;
List<Student> list = null;
try {
ObjectMapper objectMapper=new ObjectMapper();
StudentList studentList=objectMapper.readValue(str, StudentList.class);
list=studentList.getStudent();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();

for(Student s:list){
System.out.println(s.getName());
}
}

Results:

leilei
leilei02

success. . Excitement ing! ~
continue to try to add in the student inside the class attribute methods
Class stuclass {
private int classid;
private int gradeid;
}
------ Solution ----------------------------------- ---------
online there are many such third-party packages.
------ Solution ---------------------------------------- ----

- ----- Solution -------------------------------------------- which is exactly
jar package have ?
jackson-mapper-asl-1.0.0.jar
jackson-mapper-lgpl-1.0.0.jar



------ Solution ------------------------------------ --------
tools with Google 's Gson easier
------ Solution --------------------- -----------------------
flexjson also good
------ For reference only --------- ------------------------------

I know that there are many such jar package ah , this example is in fact jar package is for these applications only.
------ For reference only -------------------------------------- -
import org.codehaus.jackson.map.ObjectMapper;
jar package : jackson-core-asl-1.8.1.jar
------ For reference only -------------------- -------------------
  The reply deleted by an administrator at 2013-01-06 15:18:52

------ For reference only ---------------------------------- -----
landlord , I think you built StudentList class did their role , directly accept data when using the List not on line yet ? need so tangled it ?
----- - For reference only ---------------------------------------
just works using that learned
------ For reference only ---------------------------------- -----
then ask you, how can dynamically generate String str = "{\" student \ ": [{\" name \ ": \" leilei \ " ;, \ "age \": 23}, {\ "name \": \ "leilei02 \", \ "age \": 23}]} "; this inlay sets format json object it ?


------ For reference only ---------------------------------- -----
Google GSON easily get
------ For reference only -------------------------- -------------
encountered the same problem , the landlord or remove json that you need to add a third-party jar, is not particularly desirable , but no way to find a better solution
------ For reference only ---------------------------------------
did not know there is such a third-party package , so I wrote one , in fact, quite simple
------ For reference only --------------- ------------------------
paste code for your reference

package cn.qtone.mobile.utils;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

/ **
* the JSON data into a concrete object
* @ author jqp
*
* /
public class JsonUtil {

public static T convertToObj (JSONObject jsonObject, Class cla) {
if (jsonObject == null) return null;
Field [] fb = cla.getDeclaredFields ();
T t;
try {
t = cla.newInstance ();
for (int j = 0; j String fieldName = fb [j]. getName ();
String fieldNameU = fieldName.substring (0, 1). toUpperCase () + fieldName.substring (1);
Method method = cla.getMethod ("set" + fieldNameU, fb [j]. getType ());
method.invoke (t, jsonObject.get (fieldName));
}
return t;

} catch (SecurityException e) {
/ / TODO Auto-generated catch block
e.printStackTrace ();
} catch (IllegalArgumentException e) {
/ / TODO Auto-generated catch block
e.printStackTrace ();
} catch (IllegalAccessException e) {
/ / TODO Auto-generated catch block
e.printStackTrace ();
} catch (InstantiationException e) {
/ / TODO Auto-generated catch block
e.printStackTrace ();
} catch (NoSuchMethodException e) {
/ / TODO Auto-generated catch block
e.printStackTrace ();
} catch (InvocationTargetException e) {
/ / TODO Auto-generated catch block
e.printStackTrace ();
} catch (JSONException e) {
/ / TODO Auto-generated catch block
e.printStackTrace ();
}
return null;
}

public static List convertToList (JSONArray jsonArray, Class cla) {
List list = new ArrayList ();
if (jsonArray == null) return list;
try {
for (int i = 0; i JSONObject jsonObject = jsonArray.getJSONObject (i);
T t = JsonUtil.convertToObj (jsonObject, cla) ;
list.add (t);
}

} catch (SecurityException e) {
/ / TODO Auto-generated catch block
e.printStackTrace ();
} catch (IllegalArgumentException e) {
/ / TODO Auto-generated catch block
e.printStackTrace ();
} catch (JSONException e) {
/ / TODO Auto-generated catch block
e.printStackTrace ();
}
return list;
}

}

------ For reference only ---------------------------------- -----

------ For reference only ---------------------------------------
jsonArray.length () this line in question to jsonArray.size ()
------ For reference only ------------ ---------------------------
is org.json bag?

paste code for your reference

package cn.qtone.mobile.utils;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;



------ For reference only ---------------------------------- -----


If this is how to do [{'id': '1 ',' uname ':' Tom ',' hobbies ': [{' name ':' Running '}, {' name ':' swim '}]}, {' id ': '2', 'uname': ' Joe Smith ', 'hobbies': [{'name': ' sleep '}, {'name': ' chat '} ] } ]

没有评论:

发表评论