Android---读取与创建JSON格式的数据

关于JSON:

数据在键值对中

数据由逗号分隔

花括号保存对象

方括号保存数组


{
	"languages":[
		{"id":1,"ide":"Eclpse","name":"Java"},
		{"id":2,"ide":"XCode","name":"Swift"},
		{"id":3,"ide":"Visual Studio","name":"C#"}
	],
	"cat":"it"
}

将这个JSON格式的数据读取出来:


public class MainActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		try {
			InputStreamReader isr = new InputStreamReader(getAssets().open(
					"test.json"), "utf-8");

			BufferedReader br = new BufferedReader(isr);
			String line;
			StringBuilder sb = new StringBuilder();

			while ((line = br.readLine()) != null) {
				sb.append(line);
			}
			br.close();
			isr.close();

			JSONObject root = new JSONObject(sb.toString());
			System.out.println("cat = " + root.getString("cat"));

			JSONArray array = root.getJSONArray("languages");

			for (int i = 0; i < array.length(); i++) {
				System.out.println("-------------");
				System.out.println("id = "
						+ array.getJSONObject(i).getInt("id"));
				System.out.println("ide = "
						+ array.getJSONObject(i).getString("ide"));
				System.out.println("name = "
						+ array.getJSONObject(i).getString("name"));

			}

		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

}


Android---读取与创建JSON格式的数据_第1张图片


可以看到已经读取成功。


然后是创建一个JSON格式的数据,创建一个与上面例子一样的。



public class MainActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		try {
			JSONObject root = new JSONObject();
			root.put("cat", "it");

			JSONObject lan1 = new JSONObject();
			lan1.put("id", 1);
			lan1.put("ide", "Eclipse");
			lan1.put("name", "Java");

			JSONObject lan2 = new JSONObject();
			lan2.put("id", 2);
			lan2.put("ide", "XCode");
			lan2.put("name", "Swift");

			JSONObject lan3 = new JSONObject();
			lan3.put("id", 3);
			lan3.put("ide", "Visual Studio");
			lan3.put("name", "C#");

			JSONArray array = new JSONArray();
			array.put(lan1);
			array.put(lan2);
			array.put(lan3);
			
			root.put("languages", array);
			
			System.out.println(root.toString());

		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}




也是成功的。



你可能感兴趣的:(android,json)