首頁 >後端開發 >XML/RSS教程 >android用jsonReader來解析json

android用jsonReader來解析json

黄舟
黄舟原創
2017-02-20 15:02:461535瀏覽

對於這個json:


{
  "id" : "3232",
  "data" : [{
    "data1" : "555",
    "data2" : "3243"
    },
    {
     "data1" : "888",
     "data2" : "777"
    }]
  }


我們可以這樣來解析:



import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.io.StringReader;
import com.google.gson.stream.JsonReader;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;

public class TestActivity1 extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		parseAssertData();
	}

	public void parseAssertData() {
		InputStream is = null;
		try {
			is = this.getAssets().open("ss.json", Context.MODE_PRIVATE);
			int length = is.available();
			byte[] buffer = new byte[length];
			is.read(buffer);
			String temp = new String(buffer);

			Reader response = new StringReader(temp.toString());
			parseResponse(response);
		} catch (IOException ex) {
			ex.printStackTrace();
		}
	}

	private void parseResponse(Reader response) throws IOException {
		JsonReader reader = new JsonReader(response);
		reader.beginObject();
		while (reader.hasNext()) {
			String name = reader.nextName();
			if ("id".equals(name)) {
				String id = reader.nextString();
				System.out.println("===id="+id);
			} 
			else if (name.equals("data")) {
				reader.beginArray();
				while (reader.hasNext()) {
					  reader.beginObject();

				        String name1;
				        while (reader.hasNext()) {
				        	name1 = reader.nextName();
				            if (name1.equals("data1")) {
				            	String s1 = reader.nextString();
				            	System.out.println("===s1="+s1);
				            } else if (name1.equals("data2")) {
				            	String s2 = reader.nextString();
				            	System.out.println("===s2="+s2);
				            }  else {
				                reader.skipValue();
				            }
				        }

				        reader.endObject();
				}
				reader.endArray();
			}
			else {
				reader.skipValue();
			}
		}
		reader.endObject();
		reader.close();
	}

}

 以上就是android用jsonReader來解析json的內容,更多相關內容請關注PHP中文網(www.php.cn)!


陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn