Created
January 2, 2014 14:21
-
-
Save ishitcno1/8219805 to your computer and use it in GitHub Desktop.
Create and parse JSON in Android.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" | |
android:layout_width="match_parent" | |
android:layout_height="match_parent" | |
android:orientation="vertical"> | |
<TextView | |
android:id="@+id/main_tv_json" | |
android:layout_width="match_parent" | |
android:layout_height="wrap_content" /> | |
</LinearLayout> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.edinstudio.app.training; | |
import android.app.Activity; | |
import android.os.Bundle; | |
import android.widget.TextView; | |
import org.json.JSONArray; | |
import org.json.JSONException; | |
import org.json.JSONObject; | |
public class MainActivity extends Activity { | |
public static final String TAG = "training"; | |
private TextView mTvJson; | |
@Override | |
protected void onCreate(Bundle savedInstanceState) { | |
super.onCreate(savedInstanceState); | |
setContentView(R.layout.activity_main); | |
mTvJson = (TextView) findViewById(R.id.main_tv_json); | |
mTvJson.setText(parseJSON(createJSON())); | |
} | |
public static JSONObject createJSON() { | |
JSONObject jsonObject = new JSONObject(); | |
try { | |
jsonObject.put("name", "Albert"); | |
JSONArray score = new JSONArray(); | |
score.put(60).put(80).put(100); | |
jsonObject.put("score", score); | |
JSONObject address = new JSONObject(); | |
address.put("country", "China").put("province", "Beijing"); | |
jsonObject.put("address", address); | |
} catch (JSONException e) { | |
e.printStackTrace(); | |
} | |
return jsonObject; | |
} | |
public static String parseJSON(JSONObject jo) { | |
String s = null; | |
try { | |
JSONObject address = jo.getJSONObject("address"); | |
s = "name: " + jo.getString("name") + | |
"\n2nd score: " + jo.getJSONArray("score").getInt(1) + | |
"\naddress: " + address.getString("province") + | |
", " + address.getString("country"); | |
} catch (JSONException e) { | |
e.printStackTrace(); | |
} | |
return s; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment