方式一 1、实体类 public
class
Person {
private
int
age;
private
String name;
public
Person(
int
age, String name) {
super
();
this
.age = age;
this
.name = name;
}
@Override
public
String toString() {
return
"Person [age="
+ age +
", name="
+ name +
"]"
;
}
public
int
getAge() {
return
age;
}
public
void
setAge(
int
age) {
this
.age = age;
}
public
String getName() {
return
name;
}
public
void
setName(String name) {
this
.name = name;
}
public
Person() {
// TODO Auto-generated constructor stub
}
}
public
class
JsonList {
public
JsonList() {
// TODO Auto-generated constructor stub
}
public
static
List<Person> getList() {
List<Person> list =
new
ArrayList<Person>();
list.add(
new
Person(
1002
,
"李四2"
));
list.add(
new
Person(
1003
,
"李四3"
));
list.add(
new
Person(
1001
,
"李四1"
));
return
list;
}
public
static
Person getPerson(){
return
new
Person(
1002
,
"李四2"
);
}
}
import
net.sf.json.JSON;
import
net.sf.json.JSONArray;
import
net.sf.json.JSONObject;
import
net.sf.json.JSONSerializer;
public
class
JsonTools {
public
JsonTools() {
// TODO Auto-generated constructor stub
}
public
static
String getString(Person person) {
JSON json = JSONSerializer.toJSON(JsonList.getPerson());
return
json.toString();
}
/**
*
* @param msgString
* @return
*/
public
static
Person getPerson(String msgString) {
Person person =
new
Person();
JSONArray array =
new
JSONArray();
array.add(msgString);
JSONObject obj = array.getJSONObject(
0
);
// System.out.println(obj.get("age"));
// System.out.println(obj.get("name"));
person.setAge(obj.getInt(
"age"
));
person.setName(obj.getString(
"name"
));
return
person;
}
public
static
String getListString(List<Person> listPersons) {
JSON json = JSONSerializer.toJSON(listPersons);
return
json.toString();
}
/**
* 将一个json格式的字符串转换成行对应的对象
* @param str
* @return
*/
public
static
List<Person> getPersons(String str) {
List<Person> list =
new
ArrayList<Person>();
JSONArray array =
new
JSONArray();
array.add(str);
JSONArray array2 = array.getJSONArray(
0
);
for
(
int
i =
0
; i <array2.size(); i++) {
JSONObject jsonObject = array2.getJSONObject(i);
Person person =
new
Person();
person.setAge(jsonObject.getInt(
"age"
));
person.setName(jsonObject.getString(
"name"
));
list.add(person);
}
return
list;
}
}
1、实体类
2、服务类
方式三
1、实体类
2、服务类
方式四
1、实体类
2、服务类
|
android Json解析全
最新推荐文章于 2018-08-13 15:55:44 发布