Json для android studio

How do I parse JSON in Android? [duplicate]

How do I parse a JSON feed in Android?

3 Answers 3

Android has all the tools you need to parse json built-in. Example follows, no need for GSON or anything like that.

Get your JSON:

Assume you have a json string

Create a JSONObject:

If your json string is an array, e.g.:

then you should use JSONArray as demonstrated below and not JSONObject

To get a specific string

To get a specific boolean

To get a specific integer

To get a specific long

To get a specific double

To get a specific JSONArray:

To get the items from the array

Writing JSON Parser Class

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.

2.2. Use parser class to get JSONObject and looping through each json item. Below i am creating an instance of JSONParser class and using for loop i am looping through each json item and finally storing each json data in variable.

Источник

JSON Parsing in Android using Android Studio

Usually, most of the application require interchanging of data from the server. During interchanging data, well formatted and structured data is required. JSON parsing is good and well structured, lightweight and easy to parse and human readable. In this tutorial, we will focus how to parse to JSON in Android Studio.

JSON Parsing in Android using Android Studio

We are going to use very simple JSON in this tutorial, which contains list of students while each node have id,name,gender and phone attributes of a student.

<
«studentinfo»: [

<
«id»: «S99»,
«sname»: «Adam Jam» ,
«semail»: «adam.jam@abc.com»,
«address»: «House #33, ABC Lane, ABC CITY 06987»,
«gender» : «male»,
«phone»: <
«mobile»: «+1 1234997890»,
«home»: «00 123456»,
«office»: «00 321654»
>
>,
<
«id»: «S101»,
«sname»: «Archbould Tom»,
«semail»: «archbould.tom@axy.com»,
«address»: «House #33, ABC Lane, ABC CITY 06987»,
«gender» : «male»,
«phone»: <
«mobile»: «+1 1234599890»,
«home»: «00 123456»,
«office»: «00 321654»
>
>
]
>

Читайте также:  Blackview bv6000 обновление прошивки до андроид 8

[thrive_lead_lock >You can download the complete source code of this tutorial here.

Usually, JSON contains two types of nodes, JSONArray and JSONObject. So while parsing the JSON node we have to use the appropriate method. If JSON starts from [ represent JSONArray and if starts from < represent JSONObject.

So if JSON starting from [, we use the getJSONArray method to parse. and same as if JSON start with < we should use the getJSONObject method.

getJSONObject method.

Create new android project

Start Android Studio and create a new Android project.

We are getting JSON from the internet by making an HTTP call so we need to add internet permission in the project.

Manifest file

Handling HTTP calls

We will use separate class for making the HTTP calls, which can use both GET and POST method for HTTP calls and also could send parameters.
So create a WebRequest.JAVA class and add the following code. makeWebServiceCall(String urladdress, int requestmethod, HashMap params) should be called in order to make HTTP calls, whose parameter are
urladdress – URL which is to be called
requestmethod – HTTP request method either GET or POST
params – (Optional) if need to send any parameter with request

package com.mobilesiri.jsonparsing;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

public class WebRequest <
static String response = null;
public final static int GETRequest = 1;
public final static int POSTRequest = 2;

//Constructor with no parameter
public WebRequest() <
>
/**
* Making web service call
*
* @url — url to make web request
* @requestmethod — http request method
*/
public String makeWebServiceCall(String url, int requestmethod) <
return this.makeWebServiceCall(url, requestmethod, null);
>
/**
* Making web service call
*
* @url — url to make web request
* @requestmethod — http request method
* @params — http request params
*/
public String makeWebServiceCall(String urladdress, int requestmethod,
HashMap params) <
URL url;
String response = «»;
try <
url = new URL(urladdress);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(15001);
conn.setConnectTimeout(15001);
conn.setDoInput(true);
conn.setDoOutput(true);
if (requestmethod == POSTRequest) <
conn.setRequestMethod(«POST»);
> else if (requestmethod == GETRequest) <
conn.setRequestMethod(«GETRequest»);
>

if (params != null) <
OutputStream ostream = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(ostream, «UTF-8»));
StringBuilder requestresult = new StringBuilder();
boolean first = true;
for (Map.Entry entry : params.entrySet()) <
if (first)
first = false;
else
requestresult.append(«&»);
requestresult.append(URLEncoder.encode(entry.getKey(), «UTF-8»));
requestresult.append(«=»);
requestresult.append(URLEncoder.encode(entry.getValue(), «UTF-8»));
>
writer.write(requestresult.toString());

writer.flush();
writer.close();
ostream.close();
>
int reqresponseCode = conn.getResponseCode();

if (reqresponseCode == HttpsURLConnection.HTTP_OK) <
String line;
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((line = br.readLine()) != null) <
response += line;
>
> else <
response = «»;
>
> catch (Exception e) <
e.printStackTrace();
>
return response;
>
>

Читайте также:  Не могу зайти вконтакте андроид

We will use listview to show parsed data, so add list view in your MainActivity layout file. As our MainActivity will be ListActivit so keep list view id @android:id/list for the main list.
activity_main.xml


android:id=»@android:id/list»
android:layout_width=»match_parent»
android:layout_height=»match_parent»/>

We need a layout for listview row. Add a layout in your layout folder with name activity_main.xml and add follow XML.


android:layout_width=»match_parent»
android:layout_height=»match_parent»
android:orientation=»vertical»>

android:id=»@+id/name»
android:layout_width=»fill_parent»
android:layout_height=»wrap_content»
android:paddingBottom=»2dip»
android:paddingTop=»6dip»
android:text=»Name»
android:textSize=»16sp»
android:textStyle=»bold»/>

android:id=»@+id/email»
android:layout_width=»fill_parent»
android:layout_height=»wrap_content»
android:paddingBottom=»2dip»/>

android:id=»@+id/mobile»
android:layout_width=»wrap_content»
android:layout_height=»wrap_content»
android:gravity=»left»
android:text=»Mobile: »/>

Now, in MainActivity declare all JSON nodes and get list view reference.

public class MainActivity extends ListActivity <
// URL to get contacts JSON
private static String url = «https://raw.githubusercontent.com/mobilesiri/JSON-Parsing-in-Android/master/index.html»;

// JSON Node names
private static final String TAG_STUDENT_INFO = «studentsinfo»;
private static final String TAG_ID = «id»;
private static final String TAG_STUDENT_NAME = «sname»;
private static final String TAG_STUDENTEMAIL = «semail»;
private static final String TAG_ADDRESS = «address»;
private static final String TAG_STUDENT_GENDER = «gender»;
private static final String TAG_STUDENT_PHONE = «sphone»;
private static final String TAG_STUDENT_PHONE_MOBILE = «mobile»;
private static final String TAG_STUDENT_PHONE_HOME = «home»;

@Override
protected void onCreate(Bundle savedInstanceState) <
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

JSON Parsing

I add a method ParseJSON which is taking JSON as parameter and retuning HashMap ArrayList of data. Note getJSONArray() or getJSONObject() depend on JSON nodes.

private ArrayList > ParseJSON(String json) <
if (json != null) <
try <
// Hashmap for ListView
ArrayList > studentList = new ArrayList >();
JSONObject jsonObj = new JSONObject(json);

// Getting JSON Array node
JSONArray students = jsonObj.getJSONArray(TAG_STUDENT_INFO);

// looping through All Students
for (int i = 0; i String sname = c.getString(TAG_STUDENT_NAME);
String email = c.getString(TAG_EMAIL);
String address = c.getString(TAG_ADDRESS);
String gender = c.getString(TAG_STUDENT_GENDER);

// Phone node is JSON Object
JSONObject phone = c.getJSONObject(TAG_STUDENT_PHONE);
String mobile = phone.getString(TAG_STUDENT_PHONE_MOBILE);
String home = phone.getString(TAG_STUDENT_PHONE_HOME);

// tmp hashmap for single student
HashMap student = new HashMap ();

// adding every child node to HashMap key => value
student.put(TAG_ID, id);
student.put(TAG_STUDENT_NAME, sname);
student.put(TAG_EMAIL, email);
student.put(TAG_STUDENT_PHONE_MOBILE, mobile);

// adding student to students list
studentList.add(student);
>
return studentList;
> catch (JSONException e) <
e.printStackTrace();
return null;
>
> else <
Log.e(«ServiceHandler», «No data received from HTTP request»);
return null;
>
>

For making HTTP call to get JSON, we need to add Async class to make HTTP call in the background.
In onPreExecute method, we add a Dialog before calling the URL
In doInBackground, we call method makeWebServiceCall to get JSON and ParseJSON to parse data.
In onPostExecute I dismiss dialog, and create a list Adapter and set to ListView.

private class GetStudents extends AsyncTask <

// Hashmap for ListView
ArrayList > studentList;
ProgressDialog proDialog;

@Override
protected void onPreExecute() <
super.onPreExecute();
// Showing progress loading dialog
proDialog = new ProgressDialog(MainActivity.this);
proDialog.setMessage(«Please wait. «);
proDialog.setCancelable(false);
proDialog.show();
>

Читайте также:  Как поставить обычный андроид

@Override
protected Void doInBackground(Void. arg0) <
// Creating service handler class instance
WebRequest webreq = new WebRequest();

// Making a request to url and getting response
String jsonStr = webreq.makeWebServiceCall(url, WebRequest.GETRequest);

@Override
protected void onPostExecute(Void requestresult) <
super.onPostExecute(requestresult);
// Dismiss the progress dialog
if (proDialog.isShowing())
proDialog.dismiss();
/**
* Updating received data from JSON into ListView
* */
ListAdapter adapter = new SimpleAdapter(
MainActivity.this, studentList,
R.layout.list_item, new String[] TAG_STUDENT_PHONE_MOBILE>, new int[] R.id.email, R.id.mobile>);

>

Now run the code you will find the data is populated in ListView

Complete MainActivity

import android.app.ListActivity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListAdapter;
import android.widget.SimpleAdapter;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;

public class MainActivity extends ListActivity <

// URL to get contacts JSON
private static String url = «https://raw.githubusercontent.com/BilCode/AndroidJSONParsing/master/index.html»;

// JSON Node names
private static final String TAG_STUDENT_INFO = «studentsinfo»;
private static final String TAG_ID = «id»;
private static final String TAG_STUDENT_NAME = «sname»;
private static final String TAG_STUDENTEMAIL = «semail»;
private static final String TAG_ADDRESS = «address»;
private static final String TAG_STUDENT_GENDER = «gender»;
private static final String TAG_STUDENT_PHONE = «sphone»;
private static final String TAG_STUDENT_PHONE_MOBILE = «mobile»;
private static final String TAG_STUDENT_PHONE_HOME = «home»;

@Override
protected void onCreate(Bundle savedInstanceState) <
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

// Calling async task to get json
new GetStudents().execute();
>
/**
* Async task class to get json by making HTTP call
*/
private class GetStudents extends AsyncTask <

// Hashmap for ListView
ArrayList > studentList;
ProgressDialog proDialog;

@Override
protected void onPreExecute() <
super.onPreExecute();
// Showing progress loading dialog
proDialog = new ProgressDialog(MainActivity.this);
proDialog.setMessage(«Please wait. «);
proDialog.setCancelable(false);
proDialog.show();
>
@Override
protected Void doInBackground(Void. arg0) <
// Creating service handler class instance
WebRequest webreq = new WebRequest();

// Making a request to url and getting response
String jsonStr = webreq.makeWebServiceCall(url, WebRequest.GETRequest);

return null;
>
@Override
protected void onPostExecute(Void requestresult) <
super.onPostExecute(requestresult);
// Dismiss the progress dialog
if (proDialog.isShowing())
proDialog.dismiss();
/**
* Updating received data from JSON into ListView
* */
ListAdapter adapter = new SimpleAdapter(
MainActivity.this, studentList,
R.layout.list_item, new String[] TAG_STUDENT_PHONE_MOBILE>, new int[] R.id.email, R.id.mobile>);

>
private ArrayList > ParseJSON(String json) <
if (json != null) <
try <
// Hashmap for ListView
ArrayList > studentList = new ArrayList >();

JSONObject jsonObj = new JSONObject(json);

// Getting JSON Array node
JSONArray students = jsonObj.getJSONArray(TAG_STUDENT_INFO);

// looping through All Students
for (int i = 0; i String name = c.getString(TAG_STUDENT_NAME);
String email = c.getString(TAG_EMAIL);
String address = c.getString(TAG_ADDRESS);
String gender = c.getString(TAG_STUDENT_GENDER);

// Phone node is JSON Object
JSONObject phone = c.getJSONObject(TAG_STUDENT_PHONE);
String mobile = phone.getString(TAG_STUDENT_PHONE_MOBILE);
String home = phone.getString(TAG_STUDENT_PHONE_HOME);

// tmp hashmap for single student
HashMap student = new HashMap ();

Источник

Оцените статью