Home  >  Article  >  Backend Development  >  android uses jsonReader to parse json

android uses jsonReader to parse json

黄舟
黄舟Original
2017-02-20 15:02:461482browse

For this json:


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


We can parse it like this:



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();
	}

}

The above is the content of android using jsonReader to parse json. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn