Json parsing-use JSONObject and JSONArray in Android to parse json data
1. Code
Public class MainActivity extends Activity {
TextView TV _json;
@ Override
Protected void onCreate (Bundle savedInstanceState ){
Super. onCreate (savedInstanceState );
SetContentView (R. layout. activity_main );
TV _json = (TextView) findViewById (R. id. TV _json );
JSONObject jsonObject = new JSONObject (); // put data into it
JSONArray ja = new JSONArray (); // put the JsonObject
JSONObject jsonObject2 = new JSONObject (); // put data into it
JSONArray ja2 = new JSONArray (); // place the JsonObject
JSONObject jsonInfo = new JSONObject (); // stores jsonArray data to implement key-value
Try {
JsonObject. put ("name", "tom ");
JsonObject. put ("password", "123 ");
JsonObject. put ("sex", "man ");
JsonObject. put ("age", "20 ");
JsonObject2.put ("name2", "tom ");
JsonObject2.put ("password2", "123 ");
JsonObject2.put ("sex2", "man ");
JsonObject2.put ("age2", "20 ");
Ja. put (jsonObject );
Ja2.put (jsonObject2 );
JsonInfo. put ("first", ja );
JsonInfo. put ("second", ja2 );
System. out. println ("jsoninfo =" + jsonInfo. toString ());
TV _json.setText ("sum =" + jsonInfo. toString ());
JSONObject getJson = new JSONObject (jsonInfo. toString ());
JSONArray jArray = (JSONArray) getJson. get ("first ");
For (int I = 0; I JSONObject o = (JSONObject) jArray. get (I );
System. out. println ("o. name =" + o. getString ("name "));
}
} Catch (JSONException e ){
E. printStackTrace ();
}
}
}
2. output result:
Jsoninfo = {"second": [{"age2": "20", "sex2": "man", "name2": "tom", "password2 ": "123"}], "first": [{"password": "123", "sex": "man", "age": "20", "name ": "tom"}]}
O. name = tom
2.2 json data, unordered
{
"Second ":[
{
"Age2": "20 ",
"Sex2": "man ",
"Name2": "tom ",
"Password2": "123"
}
],
"First ":[
{
"Password": "123 ",
"Sex": "man ",
"Age": "20 ",
"Name": "tom"
}
]
}