Gson - Convert from Json to List<> - android

i'm having an issue converting Json to List<>, I have tried different solutions but no clue
My json result looks like :
{
"Return":0,
"List":[
{
"Code":524288,
"Label":"TEST"
},
{
"Code":524289,
"Label":"TEST1"
},
{
"Code":524290,
"Label":"TEST2"
}
]
}
My code :
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
List<Questionaire> qstlist = new ArrayList<Questionaire>();
try {
result = new RequestTask().execute("http:/dd.com/categories/current?owner=ccc").get();
json = new JSONObject(result);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
GsonBuilder gsonb = new GsonBuilder();
Gson gson = gsonb.create();
Type listType = new TypeToken<List<Questionaire>>(){}.getType();
qstlist = (List<Questionaire>) gson.fromJson(result, listType);
Questionaire qst = null;
qst = gson.fromJson(result, Questionaire.class);
Toast.makeText(MainActivity.this, "Result "+qstlist.size(), Toast.LENGTH_SHORT).show();
}
class RequestTask extends AsyncTask<String, String, String>{
#Override
protected String doInBackground(String... uri) {
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response;
String responseString = null;
try {
response = httpclient.execute(new HttpGet(uri[0]));
StatusLine statusLine = response.getStatusLine();
if(statusLine.getStatusCode() == HttpStatus.SC_OK){
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
responseString = out.toString();
out.close();
} else{
//Closes the connection.
response.getEntity().getContent().close();
throw new IOException(statusLine.getReasonPhrase());
}
} catch (ClientProtocolException e) {
//TODO Handle problems..
} catch (IOException e) {
//TODO Handle problems..
}
return responseString;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
}
}
My questionnaire class :
public class Questionaire {
String Code;
String Label;
public String getCode() {
return Code;
}
public void setCode(String Code) {
this.Code = Code;
}
public String getLabel() {
return Label;
}
public void setLabel(String Label) {
this.Label = Label;
}
}
Here is everything I can't see what's wrong about that

In this JSON, you get a list of {Code, Label} objects, but in the List property of an object.
You first need to encapsulate this list in an other object.
As in:
public class QuestionaireList {
public List<Questionaire> List;
}
List<Questionaire> qsts = gson.fromJson(result, QuestionaireList.class).List;

You need another class that maps the full result
public class MyJson {
#SerializedName("List")
private List<Questionaire> list;
#SerializedName("Return")
private Integer return1;
//... getters and setters
}
Your type then needs to bind to "MyJson" or whatever you name the class.

I'm assuming it's the List part you want to map to 'qstList'. If so then you need to extract it from the rest of the json first:
Gson gson = new Gson();
JsonObject resultObj = gson.fromJson(result, JsonObject.class);
JsonArray jsonList = resultObj.get("List").getAsJsonArray();
Type listType = new TypeToken<List<Questionaire>>(){}.getType();
qstList = gson.fromJson(jsonList, listType);

Related

Getting Data from JSON?

I want to get the username from this
Json url.
I have this code but it doesn't let me get the data saying
Json parsing error
Here is the code:
HttpHandler.java
public class HttpHandler {
private static final String TAG = HttpHandler.class.getSimpleName();
public HttpHandler() {
}
public String makeServiceCall(String reqUrl) {
String response = null;
try {
URL url = new URL(reqUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
// read the response
InputStream in = new BufferedInputStream(conn.getInputStream());
response = convertStreamToString(in);
} catch (MalformedURLException e) {
Log.e(TAG, "MalformedURLException: " + e.getMessage());
} catch (ProtocolException e) {
Log.e(TAG, "ProtocolException: " + e.getMessage());
} catch (IOException e) {
Log.e(TAG, "IOException: " + e.getMessage());
} catch (Exception e) {
Log.e(TAG, "Exception: " + e.getMessage());
}
return response;
}
private String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line;
try {
while ((line = reader.readLine()) != null) {
sb.append(line).append('\n');
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
private String TAG = MainActivity.class.getSimpleName();
private ProgressDialog pDialog;
private ListView lv;
// URL to get contacts JSON
private static String url = "https://someLink";
ArrayList<HashMap<String, String>> contactList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
contactList = new ArrayList<>();
lv = (ListView) findViewById(R.id.list);
new GetContacts().execute();
}
/**
* Async task class to get json by making HTTP call
*/
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
JSONArray contacts = jsonObj.getJSONArray("");
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String name = c.getString("username");
// tmp hash map for single contact
HashMap<String, String> contact = new HashMap<>();
// adding each child node to HashMap key => value
contact.put("username", name);
// adding contact to contact list
contactList.add(contact);
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG)
.show();
}
});
}
} else {
Log.e(TAG, "Couldn't get json from server.");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Couldn't get json from server. Check LogCat for possible errors!",
Toast.LENGTH_LONG)
.show();
}
});
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
MainActivity.this, contactList,
R.layout.list_item, new String[]{"username"}, new int[]{R.id.name});
lv.setAdapter(adapter);
}
}
}
This is an example i found on google and tried to change it a bit in my needs.I've put an empty JsonArray.I also tried other examples but i can't understand what is going wrong.
**
> New question
If my url is like this?What is the difference with the other?
**
You don't have an array to parse in the output. Your URL giving you an Object. Your code should be something like this
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
String name = jsonObj.getString("username");
//... now use the whereever you want
}
catch (final JSONException e) {
//... put your error log
}
Please edit your code in MainActivity to get the username from json string as follows :
if(jsonStr!=null)
{
JSONObject jsonObj = new JSONObject(jsonStr);
if(jsonObj !=null)
{
String name = jsonObj .getString("username");
}
}
i suggest you to use this one.
public class HttpGetResources extends AsyncTask<String, Void, Object> {
#SuppressLint("StaticFieldLeak")
private ProgressBar progressBar;
private static final String RAW_DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSSz";
private String urlString;
private String apiName;
private Class Response_Class;
private static final Gson GSON = new GsonBuilder().setDateFormat(RAW_DATE_FORMAT).create();
private Context context;
public HttpGetResources(Context context,Class Response_Class, String apiName, String urlString) {
this.Response_Class = Response_Class;
this.apiName = apiName;
this.urlString = urlString;
this.context=context;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(Object response) {
super.onPostExecute(response);
}
HttpURLConnection conn = null;
OutputStreamWriter out = null;
Object result = null;
BufferedReader buffer = null;
final ExecutorService executor = Executors.newCachedThreadPool(Executors.defaultThreadFactory());
static public Future<Object> future;
#SuppressWarnings("unchecked")
#Override
protected Object doInBackground(final String... params) {
// JsonObject res=null;
future = executor.submit(new Callable<Object>() {
#Override
public Object call() throws IOException {
try {
URL url = new URL(urlString + apiName);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
conn.setConnectTimeout(3000);
conn.setReadTimeout(15000);
conn.setDoInput(true);
conn.setDoOutput(true);
out = new OutputStreamWriter(conn.getOutputStream());
out.write(params[0]);
out.flush();
out.close(); out=null;
buffer = new BufferedReader(new InputStreamReader(conn.getInputStream()));
// res= GSON.fromJson(buffer, JsonObject.class);
// result = new Gson().fromJson(res.toString(), Response_Class);
result = GSON.fromJson(buffer, Response_Class);
buffer.close(); buffer=null;
// result = new Gson().fromJson(res.toString(), Response_Class);
} catch (Exception e) {
//
} finally {
if (buffer!=null) {
try {
buffer.close();
} catch (Exception e) { //
}
}
if (out != null) {
try {
out.close();
} catch (Exception e) { //
}
}
if (conn != null) {
conn.disconnect();
}
}
return result;
}
});
try {
result = future.get(10, TimeUnit.SECONDS);
} catch (Exception ignored) {
}
return result;
}
}
--and call method--
public synchronized Object HttpGetRes(final Object REQUEST_CLASS, final Class RESPONSE_CLASS, final String
API_NAME, final String URL) {
if(isNetworkAvailable()) {
response = null;
try {
Log.e(API_NAME, "url: " + URL);
Log.e(REQUEST_CLASS.getClass().getSimpleName(), new Gson().toJson(REQUEST_CLASS));
HttpGetResources resource = new HttpGetResources(BaseContext,RESPONSE_CLASS, API_NAME,
URL);
response = resource.execute(new Gson().toJson(REQUEST_CLASS)).get();
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
if (response != null) {
String x = new Gson().toJson(response);
Log.e(RESPONSE_CLASS.getSimpleName(), x);
return response;
} else {
}
}
return null;
}
Try to use GSON library in the future, it will auto convert the JSON object to a java object automatically for you. This will be useful to avoid parsing complex JSON objects or JSON arrays. https://github.com/google/gson

Convert JSONArray to Object using GSON fromJson method

I have a WCF Webservice, in which send a data model and i get this in Android by JSon(By Entity Framework),any ways,
I can successfully get that JSON by this code and store all JSON Objects in JSONArray in the AsyncTas class, and in :
public class Consume extends AsyncTask<Void, Void, Void> {
InputStream inputStream = null;
String result = "";
private ArrayList<Contact> contacts = new ArrayList<Contact>();
#Override
protected Void doInBackground(Void... params) {
String URL = "http://x.x.x.x/MyWCF/Service1.svc/rest/getContact";
ArrayList<NameValuePair> param = new ArrayList<NameValuePair>();
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost post = new HttpPost(URL);
post.setEntity(new UrlEncodedFormEntity(param));
HttpResponse httpResponse = httpClient.execute(post);
HttpEntity httpEntity = httpResponse.getEntity();
//post.setHeader("content-type", "application/json");
inputStream = httpEntity.getContent();
} catch (UnsupportedEncodingException e1) {
Log.e("UnsupportedEncoding", e1.toString());
e1.printStackTrace();
} catch (ClientProtocolException e2) {
Log.e("ClientProtocolException", e2.toString());
e2.printStackTrace();
} catch (IllegalStateException e3) {
Log.e("IllegalStateException", e3.toString());
e3.printStackTrace();
} catch (IOException e4) {
Log.e("IOException", e4.toString());
e4.printStackTrace();
}
try {
BufferedReader bReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder sBuilder = new StringBuilder();
String line = null;
while ((line = bReader.readLine()) != null) {
sBuilder.append(line + "\n");
}
inputStream.close();
result = sBuilder.toString();
} catch (Exception e) {
Log.e("StringBuilding", "Error converting result " + e.toString());
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
try {
JSONObject object = new JSONObject(result);
JSONArray jArray = object.getJSONArray("getContactResult"); //here i create the JsonArray of all JsonObjects
//Here is the solutions, We make a list of out Contact and make it as down
List<Contact> contacts;
Type listType = new TypeToken<List<Contact>>() {
}.getType();
contacts= new Gson().fromJson(String.valueOf(jArray), listType);
//And here solution is ended !
} catch (JSONException e) {
e.printStackTrace();
}
}
And i created a Contact class in android, by this code :
public class Contact {
#SerializedName("name")
private String name;
#SerializedName("lastName")
private String lastName;
#SerializedName("phoneNumber")
private String phoneNumber;
#SerializedName("latitude")
private String latitude;
#SerializedName("longitude")
private String longitude;
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getLastName() {
return lastName;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setLatitude(String latitude) {
this.latitude = latitude;
}
public String getLatitude() {
return latitude;
}
public void setLongitude(String longitude) {
this.longitude = longitude;
}
public String getLongitude() {
return longitude;
}
}
And i parse this JSONArray by Old ways !
By this method :
ArrayList<Contact> setFields(JSONArray jsonArray) {
ArrayList<Contact> contacts = new ArrayList<Contact>();
for(int i=0; i<jsonArray.length(); i++) {
try {
Contact contact = new Contact();
JSONObject object = (JSONObject) jsonArray.get(i);
contact.setName(object.getString("name"));
contact.setLastName(object.getString("lastName"));
contact.setPhoneNumber(object.getString("phoneNumber"));
contact.setLatitude(object.getString("latitude"));
contact.setLongitude(object.getString("longitude"));
contacts.add(contact);
} catch (JSONException e) {
e.printStackTrace();
}
}
return contacts;
}
It works, but I do not want to handle and parse JSONArray by this old way and wanna use GSON instead,any one can help me with this sample?
Here is my JSONArray and JSON Object :
{
"getContactResult": [
{
"id": 2041,
"lastName": "xxxx",
"latitude": xxx,
"longitude": xxx,
"name": "xxxx",
"phoneNumber": "xxxx"
}
]
}
Thx
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
List<Contact> contacts;
Type listType = new TypeToken<List<Contact>>() {
}.getType();
contacts= new Gson().fromJson(jsonArray, listType);
This should work. make sure that your model class has same name as of json parameters and datatype. it will parse the jsonarray to type List of java
This already answered but i want to share one thing for you.Easy and best way
There is one plugin Gson for android studio.You need to install.Then go to CTRL + insert.
You can create gson file.
Enter some name for java file.
Click that file then Paste you json data. Click ok.
You can see your created json to gson format.
thanks hope this will help you.
Kotlin Solution
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
val gson = Gson()
val type = object : TypeToken<List<Contact>>() {}.type
val listContact : KycProperties = gson.fromJson(jArray.toString(), type) as Contact
Java Solution
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
List<Contact> listContact;
Type type = new TypeToken<List<Contact>>() {
}.getType();
listContact= new Gson().fromJson(jsonArray.toString(), type);
Combining Gson and JSON (a different approach), Simple for newbies to understand. If your gson containing json array.
ArrayList<Sukh>sukhs new ArrayList<>();
Gson gson = new Gson();
try {
JSONArray jsonArray = new JSONArray(fullJsonArrayString);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject=jsonArray.getJSONObject(i);
Sukh sukhObject = gson.fromJson(jsonObject.toString(), Sukh.class);
sukhs.add(sukhObject);
}
} catch (JSONException e) {
e.printStackTrace();
}

populate json array in android spinner

I am getting problem to parse json in android spinner. I have tried by below listed code but I am getting full json array in spinner like screenshot
My Json Array
{"Department":[{"1":"Computer"},{"2":"IT"},{"3":"Civil"}]} // like this type json string
My Code
public class GetDropdownItems extends AsyncTask<Void, Void, String[]> {
public GetDropdownItems() {
super();
}
#Override
protected void onPreExecute() {
super.onPreExecute();
Log.i("MY_NETWORK", "first");
}
#Override
protected String[] doInBackground(Void... params) {
StringBuilder sbstaffdep = new StringBuilder();
String staffdepURL = StaticDataEntity.URL_GETDEP;
String charset = "UTF-8"; // Or in Java 7 and later, use the constant: java.nio.charset.StandardCharsets.UTF_8.name()
URLConnection connectionstaffDep = null;
try {
connectionstaffDep = new URL(staffdepURL).openConnection();
} catch (IOException e) {
e.printStackTrace();
}
connectionstaffDep.setDoOutput(true); // Triggers POST.
connectionstaffDep.setRequestProperty("Accept-Charset", charset);
connectionstaffDep.setConnectTimeout(6000);
InputStream responsestaffDep = null;
try {
responsestaffDep = connectionstaffDep.getInputStream();
} catch (IOException e) {
e.printStackTrace
();
return new String[]{"unreachable"};
}
BufferedReader brstaffDep = new BufferedReader(new InputStreamReader(responsestaffDep));
String readstaffDep;
try {
while ((readstaffDep = brstaffDep.readLine()) != null) {
//System.out.println(read);
sbstaffdep.append(readstaffDep);
}
} catch (IOException e) {
e.printStackTrace();
}
try {
brstaffDep.close();
} catch (IOException e) {
e.printStackTrace();
}
String[] finaldata = new String[1];
finaldata[0] = sbstaffdep.toString();
return finaldata;
}
#Override
protected void onPostExecute(String[] s) {
super.onPostExecute(s);
if (s[0].equals("unreachable")) {
new SweetAlertDialog(SignUpStaff.this, SweetAlertDialog.ERROR_TYPE)
.setTitleText("Oops...")
.setContentText("Unable to connect to server ! \n Please try again later.")
.setCancelText("Ok")
.setCancelClickListener(new SweetAlertDialog.OnSweetClickListener() {
#Override
public void onClick(SweetAlertDialog sweetAlertDialog) {
sweetAlertDialog.cancel();
}
})
.show();
return;
}
Log.i("MY_NETWORK", s.toString());
String[] dataofdropdowndep = s[0].split(",");
ArrayAdapter<String> adapterdep = new ArrayAdapter<String>(SignUpStaff.this, android.R.layout.simple_list_item_1, dataofdropdowndep);
adapterdep.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
dropstaffdep.setAdapter(adapterdep);
}
}
public class GetDropdownItems extends AsyncTask<Void, Void, String> {
public GetDropdownItems() {
super();
}
#Override
protected void onPreExecute() {
super.onPreExecute();
Log.i("MY_NETWORK", "first");
}
#Override
protected String doInBackground(Void... params) {
StringBuilder sbstaffdep = new StringBuilder();
String staffdepURL = StaticDataEntity.URL_GETDEP;
String charset = "UTF-8"; // Or in Java 7 and later, use the constant: java.nio.charset.StandardCharsets.UTF_8.name()
URLConnection connectionstaffDep = null;
try {
connectionstaffDep = new URL(staffdepURL).openConnection();
} catch (IOException e) {
e.printStackTrace();
}
connectionstaffDep.setDoOutput(true); // Triggers POST.
connectionstaffDep.setRequestProperty("Accept-Charset", charset);
connectionstaffDep.setConnectTimeout(6000);
InputStream responsestaffDep = null;
try {
responsestaffDep = connectionstaffDep.getInputStream();
} catch (IOException e) {
e.printStackTrace
();
return "unreachable";
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
responsestaffDep, "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();
Log.d("-------------", json);
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
return json;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
if (s.equals("unreachable")) {
new SweetAlertDialog(SignUpStaff.this, SweetAlertDialog.ERROR_TYPE)
.setTitleText("Oops...")
.setContentText("Unable to connect to server ! \n Please try again later.")
.setCancelText("Ok")
.setCancelClickListener(new SweetAlertDialog.OnSweetClickListener() {
#Override
public void onClick(SweetAlertDialog sweetAlertDialog) {
sweetAlertDialog.cancel();
}
})
.show();
return;
}
Log.i("MY_NETWORK", s.toString());
Json js=new Json(s);
JSONArray array=js.getJSONArray("Department");
for(JSONArray b:array){
// traverse array here
}
ArrayAdapter<String> adapterdep = new ArrayAdapter<String>(SignUpStaff.this, android.R.layout.simple_list_item_1, dataofdropdowndep);
adapterdep.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
dropstaffdep.setAdapter(adapterdep);
}
}
HI Change your Json Response from server or you can change manually .
Here is your format :
{"Department"
[
{
"1": "Computer"
},
{
"2": "IT"
},
{
"3": "Civil"
}
]
}
Please check it with any json viewer format online.
this type json data:
check this json array:
{
"schools": [{
"Name": "Hill View Elementary",
"SchoolID": "HVE"
}, {
"Name": "Mill View",
"SchoolID": "MVE"
}, {
"Name": "Big School",
"SchoolID": "BSC"
}]
}
your mistake is you are not putting comma between two objects
The way you are fetching the Json file is wrong, there is already Json classes that can easly get each array,object or key alone.
org.json is the library we are going to use with the JSONArray and JSONObject classes.
Before we start you should know a basic understanding of the Json file scheme :
"name":{} this is the array syntax represented by the {} symbols, this array can hold arrays,objects or keys.
[] represent and object which can hold arrays and keys too but it doesn't have name.
"key":"value" now the is key type which can hold the data or values you want and has a key to retrieve it by name.
Now here is a piece of code to fetch your file and get each part of the Json file alone and then you can populate it as you wish.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.res.Resources;
public class Fetch {
final private static String DEPARTMENT = "Department";
String [] departments ;
public void fetch(Resources r , int resourceID) {
String JsonString = readStringFromRaw(r, resourceID);
//the whole josn file is a json object even if it starts with { and ends with } so...
try {
JSONObject mainObject = new JSONObject(JsonString);
// the JSONObject throws a JSONException if there is something wrong with the syntax
JSONArray department = mainObject.getJSONArray(DEPARTMENT);
int length = department.length();
departments = new String[length];
JSONObject object;
for(int i = 0 ; i < length ; i++){
object = department.getJSONObject(i);
departments[0] = object.getString(""+i+1);
//this because you tagged the keys with 1 , 2 , 3 and so on.. so it has the value of the object that it is in + 1 .
//the reason I put "" empty quotations is because I want it a string so this is a way to cast the numbers to strings .
}
} catch (JSONException e) {
e.printStackTrace();
}
}
public static String readStringFromRaw(Resources r, int resourceID) {
InputStream is = r.openRawResource(resourceID);
BufferedReader br = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder(1000);
String line;
try {
while ((line = br.readLine()) != null)
sb.append(line);
br.close();
is.close();
return sb.toString();
} catch (IOException e) {
return e.getMessage();
}
}
}
With this class you can get a String array holding the departments you want for your json file that you have.
The heirarchy between arrays and objects is very important so keep in mind that when you write a json file make it less complicated to extract the information easier.

Parsing multiple JSON strings

I would like to thank all the users in this community for helping me get as far as I am in my project today.
I now need your help once again. So far, I am able to establish a connection in my project from this JSON link (REMOVED FOR PRIVACY CONCERNS)
The problem is I am only able to parse one string, (firstName)
Here is my code:
public class JSONActivity extends Activity {
static TextView http;
HttpClient client;
JSONObject json;
final static String URL = "REMOVED FOR PRIVACY CONCERNS
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
http = (TextView) findViewById(R.id.http);
client = new DefaultHttpClient();
new Read().execute("firstName");
}
public JSONObject getpw(String password) throws ClientProtocolException,
IOException, JSONException {
StringBuilder url = new StringBuilder(URL);
url.append(password);
HttpGet get = new HttpGet(url.toString());
HttpResponse r = client.execute(get);
int status = r.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity e = r.getEntity();
String data = EntityUtils.toString(e);
JSONObject getname = new JSONObject(data);
return getname;
} else {
Toast.makeText(JSONActivity.this, "error", Toast.LENGTH_SHORT);
return null;
}
}
public class Read extends AsyncTask<String, Integer, String> {
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
try {
json = getpw("trustme");
return json.getString("firstName");
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
http.setText(result);
}
}
}
My question is, how can I parse multiple strings rather than just "firstName"?
You can get it all by doing the following:
String firstname = json.getString("firstName");
String lastname = json.getString("lastName");
int checkedIn = json.getInt("checkedIn");
int updated = json.getInt("checkedindatetime");
JSONObject address = json.getJSONObject("address");
String streetaddress = address.getString("streetAddress");
String city = address.getString("city");
etc...
JSONArray phoneNumbers = json.getJSONArray("phoneNumber");
String type = phoneNumbers.getJSONObject(0).getString("type");
etc...
Hope this helps.
A good resource for looking at json, is this validator.

Parsing Google Shopping Json Search Results

After a few weeks of trying numerous examples found here and it seems throughout the web, I'm stumped. I can retrieve the desired search results from Google Shopping just fine:
{ "items": [ { "product": {
"title": "The Doctor's BrushPicks Toothpicks 250 Pack",
"brand": "The Doctor's" } } ] }
My problem is that I have the data sitting in a string, how do I extract the two values (title,brand) in order to use them elsewhere in the program?
Here is the class in question:
public class HttpExample extends Activity {
TextView httpStuff;
DefaultHttpClient client;
JSONObject json;
final static String URL = "https://www.googleapis.com/shopping/search...";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.httpex);
httpStuff = (TextView) findViewById(R.id.tvHttp);
client = new DefaultHttpClient();
new Read().execute("items");
}
public JSONObject products(String upc) throws ClientProtocolException, IOException, JSONException {
StringBuilder url = new StringBuilder(URL);
url.append(upc);
HttpGet get = new HttpGet(url.toString());
HttpResponse r = client.execute(get);
int status = r.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity e = r.getEntity();
String data = EntityUtils.toString(e);
JSONObject timeline = new JSONObject(data);
return timeline;
} else {
Toast.makeText(HttpExample.this, "error", Toast.LENGTH_SHORT);
return null;
}
}
public class Read extends AsyncTask<String, Integer, String> {
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
try {
String upc = ExportMenuActivity.upc;
json = products(upc);
return json.getString(params[0]);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result){
httpStuff.setText(result);
}
}
}
The output of httpStuff.setText(result):
[{"product":{"brand":"The Doctor's, "title":"The Doctor's..."}}]
A solution that'd work on all versions of Android would look something like this:
JSONObject products = products(jsonStr);
JSONArray itemArray = products.getJSONArray("items");
for(int i=0; i<itemArray.length(); i++) {
if(itemArray.isNull(i) == false) {
JSONObject item = itemArray.getJSONObject(i);
String title = item.getString("title");
String brand = item.getString("brand");
}
}
JsonReader is nice, but is only available in API 10 and up. So it might or might not work for you.
You should use a JsonReader for reading the json string. Its very easy and well documented with very good sample.. here

Categories

Resources