2016-11-14 269 views
1

我想将一个JSON列表从一个活动发送到其他活动。我做这样无法在Android中获取JSON数据

要发送

List<JSONObject> jsonList = new ArrayList<JSONObject>(); 
Intent i = new Intent(getApplicationContext(), AdapterContent.class); 
Bundle b = new Bundle(); 
b.putString("Array",jsonList.toString()); 
i.putExtras(b); 

对于接受

Bundle b = getIntent().getExtras(); 
String Array=b.getString("Array"); 
Log.i("TAG" ,Array); 
JSONObject jsonobj = new JSONObject(Array); 
Log.i("Name" , String.valueOf(jsonobj.getString("Name"))); 

JSON对象

[ 
{"Name":"Area1"}, 
{"Name":"Area 2"} 
] 

但它促使

W/System.err的:在com.example.data.mydata.onCreate

它打印Array但不是NameJsonObj 有什么不对吗?

+0

使用jsonobj.get(“姓名”),也许这将有助于 –

+2

你是什么jsonList? Json数组或Java数组? –

+0

@MdAbdulGafur是对的。你在'jsonObj'中获得的格式是什么格式通过[pastie](http://pastie.org) – Praveenkumar

回答

2
// make a json array 
JSONArray jsonArr = new JSONArray(Array); 

// empty containers for later use 
JSONObject jobj; 
String name=null; 

// traverse all json object according to index of jsonarray 
for(int i=0;i<jsonArr.length();i++){ 

// fetch jasonObject according to index 
    jobj=jsonArr.getJSONObject(i); 

// get the name string from object and use it accordingly 
    name=jobj.optString("Name"); 
} 
0

你必须转换JSON字符串转换成JSON数组不是JSON对象

String Array = getIntent().getExtras().getString("Array"); 
Log.i("TAG" ,Array); 
JSONArray jsonArr = new JSONArray(Array); 
JSONObject jsonObj; 
for(int i=0;i<jsonArr.length();i++){ 
    jsonObj = jsonArr.getJSONObject(i); 
    Log.i("Name" , String.valueOf(jsonObj.getString("Name"))); 
} 

注:建议序列化或转换数据parcelable活动

0

为什么之间时您需要发送JsonList。最好为你的List创建一个模型类。并使其可以放行。并将其发送给另一个活动

intent.putExtra(Key,yourModelClass);