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

Json解析的三种方式

2017-06-19 08:52 225 查看
解析JSON
方式一:使用org.json包解析

/**
* 通过org.json解析json
* @param jsonStr json字符串
* @throws JSONException  格式不对,转换异常
*/
public static Sentence parseJsonByOrgJson(String jsonStr) throws JSONException{
// 使用该方法解析思路,遇到大括号用JsonObject,中括号用JsonArray
// 第一个是大括号{}
JSONObject jsonObj = new JSONObject(jsonStr);
// 新建Sentence对象
Sentence sentence = new Sentence();
// 以下是无脑操作
String caption = jsonObj.getString("caption");
String content = jsonObj.getString("content");
String dateline = jsonObj.getString("dateline");
String fenxiang_img = jsonObj.getString("fenxiang_img");
String love = jsonObj.getString("love");
String note = jsonObj.getString("note");
String picture = jsonObj.getString("picture");
String picture2 = jsonObj.getString("picture2");
String s_pv = jsonObj.getString("s_pv");
String sp_pv = jsonObj.getString("sp_pv");
String translation = jsonObj.getString("translation");
String tts = jsonObj.getString("tts");
sentence.caption = caption;
sentence.content = content;
sentence.dateline = dateline;
sentence.fenxiang_img = fenxiang_img;
sentence.love = love;
sentence.note = note;
sentence.picture = picture;
sentence.picture2 = picture2;
sentence.s_pv = s_pv;
sentence.sp_pv = sp_pv;
sentence.translation = translation;
sentence.tts = tts;

// 解析关键字tags,它是一个JsonArray,遇到[]
JSONArray jsonArray = jsonObj.getJSONArray("tags");
// 新建Tag集合
List<Sentence.Tag> tags = new ArrayList<Sentence.Tag>();
for(int i=0;i<jsonArray.length();i++){
Sentence.Tag tag = new Sentence.Tag();
// jsonArray里的每一项都是JsonObject
JSONObject jsonObject = jsonArray.getJSONObject(i);
tag.id = jsonObject.getInt("id");
tag.name = jsonObject.getString("name");
tags.add(tag);
}
sentence.tags = tags;

return sentence;
}


 使用这种方法解析JSON,看注释,没什么好多的,总结一句话就是:遇到{}用JSONObject,遇到[]用JSONArray,这样你就可以说你精通org.json解析JSON了。

方式二:使用JsonReader解析JSON,JsonReader解析JSON有点类似PULL解析XML,主要的方法还是nextName()将游标后移。

/**
* Call requires API level 11 (current min is 8): new
* android.util.JsonReader 通过org.json解析json
*
* @param jsonStr
*            json字符串
* @throws Exception
*/
@SuppressLint("NewApi")
public static Sentence parseJsonByJsonReader(String jsonStr)
throws Exception {
// 新建Sentence
Sentence sentence = new Sentence();
// 新建Tag集合
List<Sentence.Tag> tags = new ArrayList<Sentence.Tag>();
JsonReader reader = new JsonReader(new StringReader(jsonStr));
// 遇到{,开始解析对象
reader.beginObject();
while (reader.hasNext()) {
String name = reader.nextName();
if ("caption".equals(name)) {
sentence.caption = reader.nextString();
}
if ("content".equals(name)) {
sentence.content = reader.nextString();
}
if ("dateline".equals(name)) {
sentence.dateline = reader.nextString();
}
if ("fenxiang_img".equals(name)) {
sentence.fenxiang_img = reader.nextString();
}
if ("love".equals(name)) {
sentence.love = reader.nextString();
}
if ("note".equals(name)) {
sentence.note = reader.nextString();
}
if ("picture".equals(name)) {
sentence.picture = reader.nextString();
}
if ("picture2".equals(name)) {
sentence.picture2 = reader.nextString();
}
if ("s_pv".equals(name)) {
sentence.s_pv = reader.nextString();
}
if ("sid".equals(name)) {
sentence.sid = reader.nextString();
}
if ("sp_pv".equals(name)) {
sentence.sp_pv = reader.nextString();
}
if ("translation".equals(name)) {
sentence.translation = reader.nextString();
}
if ("tts".equals(name)) {
sentence.tts = reader.nextString();
}
if ("tags".equals(name)) {
// 遇到[,开始解析数组
reader.beginArray();
while (reader.hasNext()) {
// 遇到{,开始解析对象
reader.beginObject();
Sentence.Tag tag = new Sentence.Tag();
if ("id".equals(reader.nextName())) {
tag.id = reader.nextInt();
}
if ("name".equals(reader.nextName())) {
tag.name = reader.nextString();
}
// 遇到},对象解析结束
reader.endObject();
tags.add(tag);
}
sentence.tags = tags;
// 遇到],数组解析结束
reader.endArray();
}
}
// 遇到},对象解析结束
reader.endObject();
return sentence;
}


JsonReader解析JSON:

当开始解析对象时(遇到"{"就JsonReader.beginObject()),当这个对象解析结束了(遇到"}")就endObject()结束对象的解析。
当开始解析数组时(遇到"["[b]就JsonReader.beginArray()),当这个数组解析结束了(遇到"]"[/b])就endArray()结束数组的解析。

注意nextXXX()都会是游标后移,如果有数据忘了解析等等导致游标错位,将会导致数据类型错乱,这个时候就会很容易发生:java.lang.IllegalStateException: Expected a X but was Y ...参数匹配异常。所以一定不要漏了数据和注意每一次移动游标。

方式三:使用GSON解析

   1、下载Gson包放到项目lib目录下面,并添加到构建路径中



gson的jar包下载:gson-2.5.jar

   2、编写JavaBean

package com.example.jsonparsedemo;

import java.util.List;

// 由于简单起见,直接用public
public class Sentence {

public String caption;
public String content;
public String dateline;
public String fenxiang_img;
public String love;
public String note;
public String picture;
public String picture2;
public String s_pv;
public String sid;
public String sp_pv;
public String translation;
public String tts;

public List<Tag> tags;

static class Tag{
public int id;
public String name;

@Override
public String toString() {
return "id=" + id + "\n" +
"name=" + name + "\n" ;
}
}

@Override
public String toString() {
return "caption=" + caption + "\n" +
"content=" + content+ "\n" +
"dateline=" + dateline+ "\n" +
"fenxiang_img=" + fenxiang_img+ "\n" +
"love=" + love + "\n" +
"note=" + note + "\n" +
"picture=" + picture + "\n" +
"picture2=" + picture2 + "\n" +
"s_pv=" + s_pv + "\n" +
"sid=" + sid + "\n" +
"sp_pv="+ sp_pv + "\n" +
"translation=" + translation + "\n" +
"tts=" + tts + "\n" +
"tags=" + tags + "\n";
}

}


 JavaBean的编写(重点):

其中属性名称和json数据的键名必须相同
内部类不必是static(亲测)
类属性可以是其他权限修饰符,包括private,并且可以不用写setter和getter(亲测)
  3、新建gson对象解析json,

/**
* 通过GSON解析json
* @param jsonStr
* @return
*/
public static Sentence parseJsonByGson(String jsonStr){
Gson gson = new Gson();
Sentence sentence = gson.fromJson(jsonStr, Sentence.class);
return sentence;
}


 就三行代码,没什么说的,到这里三种解析json的方式都介绍完了,感觉每种方式都好简单,想不精通JSON解析都难。

JsonParseUtils.java的完整代码:

package com.example.jsonparsedemo;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

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

import android.annotation.SuppressLint;
import android.util.JsonReader;

import com.google.gson.Gson;

@SuppressLint("NewApi")
public class JsonParseUtils {

/**
* 连接网络请求数据,这里使用HttpURLConnection
*/
public static String getJsonData() {
URL url = null;
String jsonData = ""; // 请求服务器返回的json字符串数据
InputStreamReader in = null; // 读取的内容(输入流)
try {
url = new URL("http://open.iciba.com/dsapi");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// 这一步会连接网络得到输入流
in = new InputStreamReader(conn.getInputStream());
// 为输入创建BufferedReader
BufferedReader br = new BufferedReader(in);
String inputLine = null;
while (((inputLine = br.readLine()) != null)) {
jsonData += inputLine;
}
in.close(); // 关闭InputStreamReader
// 断开网络连接
conn.disconnect();
} catch (Exception ex) {
ex.printStackTrace();
}
return jsonData;
}

/**
* 通过org.json解析json
*
* @param jsonStr
* json字符串
* @throws JSONException
* 格式不对,转换异常
*/
public static Sentence parseJsonByOrgJson(String jsonStr)
throws JSONException {
// 使用该方法解析思路,遇到大括号用JsonObject,中括号用JsonArray
// 第一个是大括号
JSONObject jsonObj = new JSONObject(jsonStr);
// 新建Sentence对象
Sentence sentence = new Sentence();
// 以下是无脑操作
String caption = jsonObj.getString("caption");
String content = jsonObj.getString("content");
String dateline = jsonObj.getString("dateline");
String fenxiang_img = jsonObj.getString("fenxiang_img");
String love = jsonObj.getString("love");
String note = jsonObj.getString("note");
String picture = jsonObj.getString("picture");
String picture2 = jsonObj.getString("picture2");
String s_pv = jsonObj.getString("s_pv");
String sid = jsonObj.getString("sid");
String sp_pv = jsonObj.getString("sp_pv");
String translation = jsonObj.getString("translation");
String tts = jsonObj.getString("tts");
sentence.caption = caption;
sentence.content = content;
sentence.dateline = dateline;
sentence.fenxiang_img = fenxiang_img;
sentence.love = love;
sentence.note = note;
sentence.picture = picture;
sentence.picture2 = picture2;
sentence.s_pv = s_pv;
sentence.sid = sid;
sentence.sp_pv = sp_pv;
sentence.translation = translation;
sentence.tts = tts;

// 解析关键字tags,它是一个JsonArray
JSONArray jsonArray = jsonObj.getJSONArray("tags");
// 新建Tag集合
List<Sentence.Tag> tags = new ArrayList<Sentence.Tag>();
for (int i = 0; i < jsonArray.length(); i++) {
Sentence.Tag tag = new Sentence.Tag();
// jsonArray里的每一项都是JsonObject
JSONObject jsonObject = jsonArray.getJSONObject(i);
tag.id = jsonObject.getInt("id");
tag.name = jsonObject.getString("name");
tags.add(tag);
}
sentence.tags = tags;

return sentence;
}

/**
* Call requires API level 11 (current min is 8): new
* android.util.JsonReader 通过org.json解析json
*
* @param jsonStr
* json字符串
* @throws Exception
*/
@SuppressLint("NewApi")
public static Sentence parseJsonByJsonReader(String jsonStr)
throws Exception {
// 新建Sentence
Sentence sentence = new Sentence();
// 新建Tag集合
List<Sentence.Tag> tags = new ArrayList<Sentence.Tag>();
JsonReader reader = new JsonReader(new StringReader(jsonStr));
// 遇到{,开始解析对象
reader.beginObject();
while (reader.hasNext()) {
String name = reader.nextName();
if ("caption".equals(name)) {
sentence.caption = reader.nextString();
}
if ("content".equals(name)) {
sentence.content = reader.nextString();
}
if ("dateline".equals(name)) {
sentence.dateline = reader.nextString();
}
if ("fenxiang_img".equals(name)) {
sentence.fenxiang_img = reader.nextString();
}
if ("love".equals(name)) {
sentence.love = reader.nextString();
}
if ("note".equals(name)) {
sentence.note = reader.nextString();
}
if ("picture".equals(name)) {
sentence.picture = reader.nextString();
}
if ("picture2".equals(name)) {
sentence.picture2 = reader.nextString();
}
if ("s_pv".equals(name)) {
sentence.s_pv = reader.nextString();
}
if ("sid".equals(name)) {
sentence.sid = reader.nextString();
}
if ("sp_pv".equals(name)) {
sentence.sp_pv = reader.nextString();
}
if ("translation".equals(name)) {
sentence.translation = reader.nextString();
}
if ("tts".equals(name)) {
sentence.tts = reader.nextString();
}
if ("tags".equals(name)) {
// 遇到[,开始解析数组
reader.beginArray();
while (reader.hasNext()) {
// 遇到{,开始解析对象
reader.beginObject();
Sentence.Tag tag = new Sentence.Tag();
if ("id".equals(reader.nextName())) {
tag.id = reader.nextInt();
}
if ("name".equals(reader.nextName())) {
tag.name = reader.nextString();
}
// 遇到},对象解析结束
reader.endObject();
tags.add(tag);
}
sentence.tags = tags;
// 遇到],数组解析结束
reader.endArray();
}
}
// 遇到},对象解析结束
reader.endObject();
return sentence;
}

/** * 通过GSON解析json * @param jsonStr * @return */ public static Sentence parseJsonByGson(String jsonStr){ Gson gson = new Gson(); Sentence sentence = gson.fromJson(jsonStr, Sentence.class); return sentence; }
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: