码迷,mamicode.com
首页 > 移动开发 > 详细

android用jsonReader来解析json

时间:2014-08-05 00:42:38      阅读:296      评论:0      收藏:0      [点我收藏+]

标签:jsonreader

对于这个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,布布扣,bubuko.com

android用jsonReader来解析json

标签:jsonreader

原文地址:http://blog.csdn.net/baidu_nod/article/details/38377039

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!