java解析json格式数据
java返回json数据
方式1、自己全部手动写
这种方法是用servlet的内置对象response返回到前台。注意,java里的引号要用的转义字符“\”)
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {response.setCharacterEncoding("utf-8");
response.setContentType("application/json;charset=utf-8");
PrintWriter out = response.getWriter();
//或:ServletOutputStream out = response.getOutputStream();
//但两个不要一起用!
out.write("[{\"id\":1,\"name\":default}]");
out.flush();
out.close();
}
方式2、jackson解析,SpringMVC内置的解析器
示例1
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {response.setCharacterEncoding("utf-8");
response.setContentType("application/json;charset=utf-8");
PrintWriter out = response.getWriter();
Object result = new Object();
// jackson核心对象
ObjectMapper objectMap = new ObjectMapper();
objectMap.writeValue(out, result );
}
示例2
public class JackSonTest {//解析
@Test
public void test1() throws Exception{
// 对象嵌套数组嵌套对象
String json1 = "{\"id\":1,\"name\":\"JAVAEE-1703\",\"stus\":[{\"id\":101,\"name\":\"刘一\",\"age\":16}]}";
// 数组
String json2 = "[\"北京\",\"天津\",\"杭州\"]";
//1、
ObjectMapper mapper=new ObjectMapper();
Grade grade=mapper.readValue(json1, Grade.class);
System.out.println(grade);
//2、
ArrayList<String> list=mapper.readValue(json2,
new TypeReference<ArrayList<String>>() {
});
System.out.println(list);
}
//生成
@Test
public void test2() throws JsonProcessingException{
ArrayList<Student> list=new ArrayList<>();
for(int i=1;i<3;i++){
list.add(new Student(101+i, "码子", 20+i));
}
Grade grade=new Grade(100001,"张三", list);
ObjectMapper mapper=new ObjectMapper();
//将对象转换为JSON格式字符串
String json=mapper.writeValueAsString(grade);
System.out.println(json);
}
}
相关jar包
jackson-core-2.2.3.jar
jackson-annotations-2.2.3.jar
jackson-databind-2.2.3.jar
方式3、用Spring框架@ResponseBody的注解
@RequestMapping("/login")@ResponseBody
public User login(User user){
return user;
}
User字段:userName pwd。前台接收到的数据为:\'{"userName":"xxx","pwd":"xxx"}\'
效果等同于如下代码:
@RequestMapping("/login")public void login(User user, HttpServletResponse response){
response.getWriter.write(JSONObject.fromObject(user).toString());
}
方式4、传统的JSON解析
生成json字符串
public static String createJsonString(String key, Object value) {JSONObject jsonObject = new JSONObject();
jsonObject.put(key, value);
return jsonObject.toString();
}
json解析,示例1
import java.util.ArrayList;import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.json.JSONArray;
import org.json.JSONObject;
import com.android.myjson.domain.Person;
/**
* 完成对json数据的解析
*
*/
public class JsonTools {
public static Person getPerson(String key, String jsonString) {
Person person = new Person();
try {
JSONObject jsonObject = new JSONObject(jsonString);
JSONObject personObject = jsonObject.getJSONObject("person");
person.setId(personObject.getInt("id"));
person.setName(personObject.getString("name"));
person.setAddress(personObject.getString("address"));
} catch (Exception e) {
// TODO: handle exception
}
return person;
}
public static List getPersons(String key, String jsonString) {
List list = new ArrayList();
try {
JSONObject jsonObject = new JSONObject(jsonString);
// 返回json的数组
JSONArray jsonArray = jsonObject.getJSONArray(key);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject2 = jsonArray.getJSONObject(i);
Person person = new Person();
person.setId(jsonObject2.getInt("id"));
person.setName(jsonObject2.getString("name"));
person.setAddress(jsonObject2.getString("address"));
list.add(person);
}
} catch (Exception e) {
// TODO: handle exception
}
return list;
}
public static List getList(String key, String jsonString) {
List list = new ArrayList();
try {
JSONObject jsonObject = new JSONObject(jsonString);
JSONArray jsonArray = jsonObject.getJSONArray(key);
for (int i = 0; i < jsonArray.length(); i++) {
String msg = jsonArray.getString(i);
list.add(msg);
}
} catch (Exception e) {
// TODO: handle exception
}
return list;
}
public static List> listKeyMaps(String key,
String jsonString) {
List> list = new ArrayList>();
try {
JSONObject jsonObject = new JSONObject(jsonString);
JSONArray jsonArray = jsonObject.getJSONArray(key);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject2 = jsonArray.getJSONObject(i);
Map map = new HashMap();
Iterator iterator = jsonObject2.keys();
while (iterator.hasNext()) {
String json_key = iterator.next();
Object json_value = jsonObject2.get(json_key);
if (json_value == null) {
json_value = "";
}
map.put(json_key, json_value);
}
list.add(map);
}
} catch (Exception e) {
// TODO: handle exception
}
return list;
}
}
json解析,示例2
public class JSONTest {//解析JSON
@Test
public void test1() throws JSONException{
//对象嵌套数组嵌套对象
String json1="{\'id\':1,\'name\':\'JAVAEE-1703\',\'stus\':[{\'id\':101,\'name\':\'刘一\',\'age\':16}]}";
//数组
String json2="[\'北京\',\'天津\',\'杭州\']";
//1、
//解析第一层---对象
JSONObject jObject1=new JSONObject(json1);
Grade grade=new Grade();
grade.setId(jObject1.getInt("id"));
grade.setName(jObject1.getString("name"));
ArrayList<Student> stus=new ArrayList<>();
grade.setStus(stus);
//解析第二层----数组
JSONArray jsonArray2=jObject1.getJSONArray("stus");
//遍历数组获取元素----对象
for(int i=0;i<jsonArray2.length();i++){
//解析第三层----对象
JSONObject jObject3=jsonArray2.getJSONObject(i);
Student student=new Student(jObject3.getInt("id"), jObject3.getString("name"), jObject3.getInt("age"));
grade.getStus().add(student);
}
System.out.println(grade);
//获取当前对象的所有属性的迭代器对象
// Iterator<String> iterator=jObject1.keys();
// while (iterator.hasNext()) {
// String key = iterator.next();
// System.out.println("属性:"+key);
// }
//2、
//获取数组对象
JSONArray jArray=new JSONArray(json2);
ArrayList<String> list=new ArrayList<>();
//遍历获取元素
for(int i=0;i<jArray.length();i++){
//jArray.optString(i);//等价于getXXX
list.add(jArray.getString(i));
}
System.out.println("解析结果:"+list);
}
//生成JSON
@Test
public void test2() throws JSONException{
JSONObject jo1=new JSONObject();
jo1.put("id", 1001);
jo1.put("name", "范老");
jo1.put("age", 20);
JSONObject jo2=new JSONObject();
jo2.put("id", 1002);
jo2.put("name", "平平");
jo2.put("age", 19);
JSONArray ja2=new JSONArray();
ja2.put(jo1);
ja2.put(jo2);
JSONObject jo3=new JSONObject();
jo3.put("id", 11);
jo3.put("name", "JAVAEE-1704");
jo3.put("stus",ja2);
String json=jo3.toString();
System.out.println(json);
}
}
方式5、JSON解析之GSON
生成JSON字符串
import com.google.gson.Gson;public class JsonUtils {
public static String createJsonObject(Object obj) {
Gson gson = new Gson();
String str = gson.toJson(obj);
return str;
}
}
解析,示例1
import java.util.ArrayList;import java.util.List;
import java.util.Map;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
;
public class GsonTools {
public GsonTools() {
// TODO Auto-generated constructor stub
}
/**
* @param
* @param jsonString
* @param cls
* @return
*/
public static T getPerson(String jsonString, Class cls) {
T t = null;
try {
Gson gson = new Gson();
t = gson.fromJson(jsonString, cls);
} catch (Exception e) {
// TODO: handle exception
}
return t;
}
/**
* 使用Gson进行解析 List
*
* @param
* @param jsonString
* @param cls
* @return
*/
public static List getPersons(String jsonString, Class cls) {
List list = new ArrayList();
try {
Gson gson = new Gson();
list = gson.fromJson(jsonString, new TypeToken>() {
}.getType());
} catch (Exception e) {
}
return list;
}
/**
* @param jsonString
* @return
*/
public static List getList(String jsonString) {
List list = new ArrayList();
try {
Gson gson = new Gson();
list = gson.fromJson(jsonString, new TypeToken>() {
}.getType());
} catch (Exception e) {
// TODO: handle exception
}
return list;
}
public static List> listKeyMaps(String jsonString) {
List> list = new ArrayList>();
try {
Gson gson = new Gson();
list = gson.fromJson(jsonString,
new TypeToken>>() {
}.getType());
} catch (Exception e) {
// TODO: handle exception
}
return list;
}
}
示例2
public class GSONTest {//解析
@Test
public void test1() {
// 对象嵌套数组嵌套对象
String json1 = "{\'id\':1,\'name\':\'JAVAEE-1703\',\'stus\':[{\'id\':101,\'name\':\'刘一\',\'age\':16}]}";
// 数组
String json2 = "[\'北京\',\'天津\',\'杭州\']";
Gson gson=new Gson();
//1、
//解析对象:第一个参数:待解析的字符串 第二个参数结果数据类型的Class对象
Grade grade=gson.fromJson(json1, Grade.class);
System.out.println(grade);
//2、
//解析数组要求使用Type
ArrayList<String> list=gson.fromJson(json2,
new TypeToken<ArrayList<String>>(){}.getType());
System.out.println(list);
}
//生成
@Test
public void test2(){
ArrayList<Student> list=new ArrayList<>();
for(int i=1;i<3;i++){
list.add(new Student(101+i, "码子", 20+i));
}
Grade grade=new Grade(100001,"张三", list);
Gson gson=new Gson();
//将对象转换为诶JSON格式字符串
String json=gson.toJson(grade);
System.out.println(json);
}
}
方式6、JSON解析之FastJSON
示例1
import java.util.ArrayList;import java.util.List;
import java.util.Map;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
public class JsonTool {
public static T getPerson(String jsonstring, Class cls) {
T t = null;
try {
t = JSON.parseObject(jsonstring, cls);
} catch (Exception e) {
// TODO: handle exception
}
return t;
}
public static List getPersonList(String jsonstring, Class cls) {
List list = new ArrayList();
try {
list = JSON.parseArray(jsonstring, cls);
} catch (Exception e) {
// TODO: handle exception
}
return list;
}
public static List> getPersonListMap1(
String jsonstring) {
List> list = new ArrayList>();
try {
list = JSON.parseObject(jsonstring,
new TypeReference>>() {
}.getType());
} catch (Exception e) {
// TODO: handle exception
}
return list;
}
}
示例2
public class FASTJson {//解析
@Test
public void test1() {
// 对象嵌套数组嵌套对象
String json1 = "{\'id\':1,\'name\':\'JAVAEE-1703\',\'stus\':[{\'id\':101,\'name\':\'刘铭\',\'age\':16}]}";
// 数组
String json2 = "[\'北京\',\'天津\',\'杭州\']";
//1、
//静态方法
Grade grade=JSON.parseObject(json1, Grade.class);
System.out.println(grade);
//2、
List<String> list=JSON.parseArray(json2, String.class);
System.out.println(list);
}
//生成
@Test
public void test2(){
ArrayList<Student> list=new ArrayList<>();
for(int i=1;i<3;i++){
list.add(new Student(101+i, "码子", 20+i));
}
Grade grade=new Grade(100001,"张三", list);
String json=JSON.toJSONString(grade);
System.out.println(json);
}
}
示例3
String a = "{\"name\":\"jack\",\"age\":\"20\"}";public static Map<String,Object> jsonMap(String json){
return JSON.parseObject(json, Map.class);
}
Map<String,Object> b = JsonUtils.jsonMap(a);
System.out.println(b);//{age=20, name=jack}
以上是 java解析json格式数据 的全部内容, 来源链接: utcz.com/z/392019.html