欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

android用jsonReader来解析json

程序员文章站 2022-03-19 18:41:31
...
对于这个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)!