Android中生成、使用Json数据实例
作者:junjie 时间:2023-02-04 15:01:24
1、Json的制作
package com.example.usingjson2;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.Bundle;
import android.app.Activity;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
System.out.println("\"Hello World\"");
JSONObject object = new JSONObject();
try {
object.put("one", "yu");
object.put("two", "xi");
object.put("three", "kuo");
object.put("four", "hi");
System.out.println(object);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
2、Json的使用
(1)首先在当前包中创建新的class
package com.example.useingjson;
public class Data {
public static final String jsonStr = "{'arr':[1,2,3,4],'dat':[yu,xi,kuo]}";
}
(2)在Activity中调用
package com.example.useingjson;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.Bundle;
import android.app.Activity;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
System.out.println(Data.jsonStr);
try {
JSONObject jsonObject = new JSONObject(Data.jsonStr);
JSONArray jsonArray = jsonObject.getJSONArray("arr");
System.out.println(jsonArray);
for(int i = 0; i < jsonArray.length(); i++)
{
System.out.println(jsonArray.get(i));
}
JSONArray jsonArray2 = jsonObject.getJSONArray("dat");
System.out.println(jsonArray2);
for(int j = 0; j < jsonArray2.length(); j++)
{
System.out.println(jsonArray2.get(j));
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
3、注意
Json的制作与使用分别是两个项目,由于刚接触Android,代码比较简单,重在理解原理。