您的位置:首页 > Web前端 > JavaScript

JSON与GSON

2016-07-01 08:33 351 查看
JSON数据结构(可读性较差)
1.对象结构{"name":"value","nam":"val"}
2.数组结构[e1,e2,e3]["a","b","c"]

 

 

 <name>tomg</name> xml格式

 {"name":"tom"} json格式

 

 <student id="10086">

  <name>tom</name>

  <age>12</age>

  <gender>男</gender>

 </student>

 

 {"id":10086,"name":"tom","age":12,"gender":"男"}

 

 

 <class>
<student id="10000">xin</student>
<student id="100001">lai</student>
<student id="100002">feng</student>
<worker id="100003">li</worker>
<worker id="100004">guo</worker>

</class>

[{"id":10086,"name":"xin"},{"id":10010,"name":"lai"},{"id":10000,"name":"feng"}]

--------------------------------------------------------------------------------

JSON解析

org.json
JSONObject
JSONArray
gson:将数据解析成一个对象,然后将对象写出来就OK了

-------------------------------------------------------------------------------------------------------------------

使用框架进行解析:底层代码原理

package man;

import java.lang.reflect.Field;

import org.json.JSONException;

import org.json.JSONObject;

public class JSON {
//将json字符串转化成class对象
public static <T> T fromJSON(String json,Class<T> c){
T t=null;
try {
t=c.newInstance();//InstantiationException - 如果此 Class 表示一个抽象类、接口、数组类、基本类型或 void; 或者该类没有 null 构造方法; 
//或者由于其他某种原因导致实例化失败。

JSONObject obj=new JSONObject(json);
Field[]field=c.getDeclaredFields();
for (Field f : field) {
String name=f.getName();
Object o=obj.get(name);
f.setAccessible(true);
f.set(t, o);
}
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

return t;
}
//将对象转化成json字符串
public static String toJSON(Object obj){
JSONObject o=new JSONObject();

//String json="";
//获取obj的class对象
Class<?>cla=obj.getClass();
//获取所有的属性
Field[]field=cla.getDeclaredFields();
for (Field f : field) {
String name=f.getName();
System.out.println(f.getName());
f.setAccessible(true);
try {
Object val=f.get(obj);
o.put(name, val);
} catch (IllegalArgumentException | IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}
return o.toString();
}

}

--------------------------------------------------------------

Test测试类

public class Test {

public static void main(String[] args) {
// TODO Auto-generated method stub
Student stu1=new Student(43536, "jim", "IOS", "男", 56);

//JSON j=new JSON();
String man=JSON.toJSON(stu1);
System.out.println(man);

String json="{\"id\":685324,\"denger\":\"男\",\"age\":99,\"classname\":\"android\",\"name\":\"liebao\"}";
// Student stu2=null;
Student stu2=JSON.fromJSON(man, Student.class);//构造方法Student要有无参的,不然会出现错误java.lang.InstantiationException
//导错类也会出现相同错误
System.out.println(stu2);

}

}

后面还需加一个Student类,需要一个无参的构造方法

----------------------------------------------------------------------------

json解析:

package jsonfile;

import java.io.BufferedReader;

import java.io.FileNotFoundException;

import java.io.FileReader;

import java.io.IOException;

import org.json.JSONArray;

import org.json.JSONException;

import org.json.JSONObject;

public class Test1 {

public static void main(String[] args) {
// TODO Auto-generated method stub
String json="";
try {
BufferedReader br=new BufferedReader(new FileReader("xin\\GetFeeds.txt"));
json=br.readLine();
br.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
JSONObject obj=new JSONObject(json);
JSONArray ary=obj.getJSONObject("paramz").getJSONArray("feeds");
for(int i=0;i<ary.length();i++){
String subject=ary.getJSONObject(i).getJSONObject("data").getString("subject");
System.out.println(subject);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}

}

----------------------------------------------------------------------------------------------------------------

json解析2:使用fileinputstream解析

package jsonfile;

import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.io.FileReader;

import java.io.IOException;

import org.json.JSONArray;

import org.json.JSONException;

import org.json.JSONObject;

public class Test {

public static void main(String[] args) {
// TODO Auto-generated method stub
readfile();
}
public static void readfile(){
try {
FileInputStream fis=new FileInputStream("xin\\GetFeeds.txt");
int r;
StringBuffer str=new StringBuffer();
byte[]b=new byte[1024];
while(-1!=(r=fis.read(b))){
//System.out.println(fis.read(b,0,r));不能将这句话输进来,不然会出现读到的str不完整
String st=new String(b, 0, r);
str.append(st);
}
fis.close();
String msg=str.toString();//要将StringBuffer转化回String才行,不然json会报错,提示找不到内容
System.out.println(str);
JSONObject  obj=new JSONObject(msg);
System.out.println(obj.getString("status"));
JSONObject obj1=obj.getJSONObject("paramz");
JSONArray array=obj1.getJSONArray("feeds");
for(int i=0;i<array.length();i++){
if(i<array.length()-4){
//System.out.println("进入到第"+(i+1)+"条新闻");
JSONObject obj2=array.getJSONObject(i);
JSONObject obj3=obj2.getJSONObject("data");
String subject=obj3.getString("subject");
System.out.println(subject);
}else{

}
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}

}

----------------------------------------------------------------------------

gson解析网页数据:

package netJson;

import java.io.IOException;

import javax.xml.ws.Response;

import com.google.gson.Gson;

import okhttp3.OkHttpClient;

import okhttp3.Request;

public class GetTicket {

public static void main(String[] args) {
// TODO Auto-generated method stub
String url="http://piao.163.com/m/movie/list.html?app_id=2&mobileType=iPhone&ver=2.5&channel=lede&deviceId=C1985DD9-0125-4AB5-B66B-B91A85824BBA&apiVer=11&city=110000";
String json=getJSON(url);
//System.out.println(json);

Root root=new Gson().fromJson(json, Root.class);
//System.out.println(root.getRetdesc());
for(Film f:root.getList()){
System.out.println(f.getName()+"--"+f.getActors());
}
}

public static String getJSON(String url){
String json=null;
OkHttpClient client=new OkHttpClient();
Request request=new Request.Builder().url(url).build();
try {
okhttp3.Response response=client.newCall(request).execute();
if(response.isSuccessful()){
json=response.body().string();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return json;
}

}

从最外边的那个类一层层拨开,达到最后一个,这个视情况而定
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  json gson 解析