Android에서 JSON을 구문 분석하는 방법 [복제]
이 질문에는 이미 답변이 있습니다.
- Java에서 JSON을 구문 분석하는 방법 31 답변
Android에서 JSON 피드를 구문 분석하려면 어떻게합니까?
Android에는 json 내장 구문 분석에 필요한 모든 도구가 있습니다. 예를 들어 GSON이나 그와 비슷한 것이 필요하지 않습니다.
JSON을 얻으십시오 :
JSON 문자열이 있다고 가정하십시오.
String result = "{\"someKey\":\"someValue\"}";
JSONObject를 만듭니다 .
JSONObject jObject = new JSONObject(result);
json 문자열이 배열 인 경우
String result = "[{\"someKey\":\"someValue\"}]"
그런 다음 JSONArray
아래에 설명 된대로 사용해야합니다.JSONObject
특정 문자열을 얻으려면
String aJsonString = jObject.getString("STRINGNAME");
특정 부울을 얻으려면
boolean aJsonBoolean = jObject.getBoolean("BOOLEANNAME");
특정 정수를 얻으려면
int aJsonInteger = jObject.getInt("INTEGERNAME");
긴 특정을 얻으려면
long aJsonLong = jObject.getLong("LONGNAME");
특정 더블을 얻으려면
double aJsonDouble = jObject.getDouble("DOUBLENAME");
특정 JSONArray 를 얻으려면 :
JSONArray jArray = jObject.getJSONArray("ARRAYNAME");
배열에서 항목을 가져 오려면
for (int i=0; i < jArray.length(); i++)
{
try {
JSONObject oneObject = jArray.getJSONObject(i);
// Pulling items from the array
String oneObjectsItem = oneObject.getString("STRINGNAMEinTHEarray");
String oneObjectsItem2 = oneObject.getString("anotherSTRINGNAMEINtheARRAY");
} catch (JSONException e) {
// Oops
}
}
JSON 파서 클래스 작성
public class JSONParser { static InputStream is = null; static JSONObject jObj = null; static String json = ""; // constructor public JSONParser() {} public JSONObject getJSONFromUrl(String url) { // Making HTTP request try { // defaultHttpClient DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(url); HttpResponse httpResponse = httpClient.execute(httpPost); HttpEntity httpEntity = httpResponse.getEntity(); is = httpEntity.getContent(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { BufferedReader reader = new BufferedReader(new InputStreamReader( is, "iso-8859-1"), 8); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } is.close(); json = sb.toString(); } catch (Exception e) { Log.e("Buffer Error", "Error converting result " + e.toString()); } // try parse the string to a JSON object try { jObj = new JSONObject(json); } catch (JSONException e) { Log.e("JSON Parser", "Error parsing data " + e.toString()); } // return JSON String return jObj; } }
Parsing JSON Data
Once you created parser class next thing is to know how to use that class. Below i am explaining how to parse the json (taken in this example) using the parser class.2.1. Store all these node names in variables: In the contacts json we have items like name, email, address, gender and phone numbers. So first thing is to store all these node names in variables. Open your main activity class and declare store all node names in static variables.
// url to make request private static String url = "http://api.9android.net/contacts"; // JSON Node names private static final String TAG_CONTACTS = "contacts"; private static final String TAG_ID = "id"; private static final String TAG_NAME = "name"; private static final String TAG_EMAIL = "email"; private static final String TAG_ADDRESS = "address"; private static final String TAG_GENDER = "gender"; private static final String TAG_PHONE = "phone"; private static final String TAG_PHONE_MOBILE = "mobile"; private static final String TAG_PHONE_HOME = "home"; private static final String TAG_PHONE_OFFICE = "office"; // contacts JSONArray JSONArray contacts = null;
2.2. Use parser class to get
JSONObject
and looping through each json item. Below i am creating an instance ofJSONParser
class and using for loop i am looping through each json item and finally storing each json data in variable.// Creating JSON Parser instance JSONParser jParser = new JSONParser(); // getting JSON string from URL JSONObject json = jParser.getJSONFromUrl(url); try { // Getting Array of Contacts contacts = json.getJSONArray(TAG_CONTACTS); // looping through All Contacts for(int i = 0; i < contacts.length(); i++){ JSONObject c = contacts.getJSONObject(i); // Storing each json item in variable String id = c.getString(TAG_ID); String name = c.getString(TAG_NAME); String email = c.getString(TAG_EMAIL); String address = c.getString(TAG_ADDRESS); String gender = c.getString(TAG_GENDER); // Phone number is agin JSON Object JSONObject phone = c.getJSONObject(TAG_PHONE); String mobile = phone.getString(TAG_PHONE_MOBILE); String home = phone.getString(TAG_PHONE_HOME); String office = phone.getString(TAG_PHONE_OFFICE); } } catch (JSONException e) { e.printStackTrace(); }
I've coded up a simple example for you and annotated the source. The example shows how to grab live json and parse into a JSONObject
for detail extraction:
try{
// Create a new HTTP Client
DefaultHttpClient defaultClient = new DefaultHttpClient();
// Setup the get request
HttpGet httpGetRequest = new HttpGet("http://example.json");
// Execute the request in the client
HttpResponse httpResponse = defaultClient.execute(httpGetRequest);
// Grab the response
BufferedReader reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent(), "UTF-8"));
String json = reader.readLine();
// Instantiate a JSON object from the request response
JSONObject jsonObject = new JSONObject(json);
} catch(Exception e){
// In your production code handle any errors and catch the individual exceptions
e.printStackTrace();
}
Once you have your JSONObject
refer to the SDK for details on how to extract the data you require.
참고URL : https://stackoverflow.com/questions/9605913/how-do-i-parse-json-in-android
'Programming' 카테고리의 다른 글
왜 파이썬에서 0, 0 == (0, 0)이 (0, False) (0) | 2020.07.19 |
---|---|
jQuery에서 버튼 클릭 이벤트를 처리하는 방법은 무엇입니까? (0) | 2020.07.19 |
git가“당신이 의미 한”제안을 어떻게 할 수 있습니까? (0) | 2020.07.18 |
HTML5 YouTube 동영상 강제 (0) | 2020.07.18 |
Haskell에서 그래프를 어떻게 표현합니까? (0) | 2020.07.18 |