How to parse a JSON without key in android? - android

Hi i am having a simple type of json response ,I have worked on JSON with keys but in this response i only have the values,Please see the response as below
json
{
status: "success",
country: [
{
1: "Afghanistan"
},
{
2: "Albania"
},
{
3: "Algeria"
},
{
4: "American Samoa"
},
{
5: "Andorra"
},
{
6: "Angola"
},
{
7: "Anguilla"
},
{
8: "Antarctica"
},
{
9: "Antigua and Barbuda"
},
{
10: "Argentina"
},
{.....
.
.
.
.
.so on..
So i want to parse this JSON and want to put both the values in an ArrayList of Hashmap,I have worked as below,But find no path to proceed,Hope some buddy will help me.
code
jsonObj = new JSONObject(jsonStr);
if (jsonObj.has("country")) {
CountryArray = jsonObj.getJSONArray("country");
if (CountryArray != null && CountryArray.length() != 0) {
// looping through All Contacts
System.out
.println("::::::::::::::::my talent size:::::::::::"
+ CountryArray.length());

Your Json is not correct please check below format for your requirement.
{
status: "success",
country: [
{
"name": "Afghanistan",
"value": 1
},
{
"name": "Albania",
"value": 2
},
{
"name": "Algeria",
"value": 3
},
{
"name": "American Samoa",
"value": 4
},
{
"name": "Andorra",
"value": 5
},
{
"name": "Angola",
"value": "6"
}
....
....
....
]
}

The "status","country" and all the "1","2", etc in the json array "country" are all keys and hence, must be in double quotes. In short, your JSON is invalid.
Example:
{
"status": "success",
"country": [
{
"1": "Afghanistan"
}
]}

I have done it my way and wasted time in changing JSON syntax as answers suggested,my code is as below.
code
String jsonStr = sh.makeServiceCall(allContriesURL,
BackendAPIService.GET);
try {
if (jsonStr != null) {
jsonObj = new JSONObject(jsonStr);
if (jsonObj.has("country")) {
CountryArray = jsonObj.getJSONArray("country");
if (CountryArray != null && CountryArray.length() != 0) {
// looping through All Contacts
System.out
.println("::::::::::::::::my talent size:::::::::::"
+ CountryArray.length());
for (int i = 0; i < CountryArray.length(); i++) {
JSONObject c = CountryArray.getJSONObject(i);
country_name = c.getString((i + 1) + "");
System.out
.println(":::::::::::::::::::COUNTRY NAME:::::::::::::::::::::"
+ country_name);
HashMap<String, String> countryMap = new HashMap<String, String>();
countryMap.put("country_id", i + 1 + "");
countryMap.put("name", country_name);
countryList.add(countryMap);
}
}
}
}
} catch (Exception e) {
System.out
.println("::::::::::::::::::::::;;EXCEPTION::::::::::::::::"
+ e);
}

Related

Reading data from a json file in Android and put it in an array

if i have a json file like that
{
"users": [{
"name": "aa",
"address": "a"
},
{
"name ": "bb",
"address": "b"
},
{
"name": "cc",
"address": "c"
},
]}
how to read this json file and put all names in a String array in android
i used this code but in second loop it catches exception
public void loadJSONFromAsset() {
String json = null;
try {
InputStream is = getAssets().open("data.json");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
}
try {
JSONObject obj = new JSONObject(json);
JSONArray m_jArry = obj.getJSONArray("users");
for (int i = 0; i < m_jArry.length(); i++) {
JSONObject jo_inside = m_jArry.getJSONObject(i);
names.add(jo_inside.getString("name"));
images.add(jo_inside.getString("address"));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
That Json object 2nd element in the array has space next to name you can solve by 2 ways.
As your backend guys to change that
You solve the problem like this,
Change getString to optString like this
for (int i = 0; i < m_jArry.length(); i++) {
JSONObject jo_inside = m_jArry.getJSONObject(i);
String name = jo_inside.optString("name");
if(TextUtils.isEmpty(name)) {
name = jo_inside.optString("name "); // that object have space
}
names.add(name);
images.add(jo_inside.getString("address"));
}
Your Json file contain wrong format JSON.
Remove , from the last array element
{
"name": "cc",
"address": "c"
},
The valid Json should be:
{
"users": [{
"name": "aa",
"address": "a"
},
{
"name": "bb",
"address": "b"
},
{
"name": "cc",
"address": "c"
}
]
}
You have problem in your JSON string only. In second JSON name field has extra space. And also there is , after last JSON },
{
"users": [{
"name":"aa",
"address":"a"
},
{
"name":"bb",
"address":"b"
},
{
"name":"cc",
"address":"c"
}
]
}

Android Create Json Object String From Data

I want to create Json String like this from available data,
Json String:
{
"1": {
"attendance_user_status": 1
},
"2": {
"attendance_user_status": 0
},
"3": {
"attendance_user_status": 1
},
"4": {
"attendance_user_status": 1
},
"5": {
"attendance_user_status": 1
},
"6": {
"attendance_user_status": 0
},
"7": {
"attendance_user_status": 1
}, ...
}
I wrote this java code..
public String jsonCreator(ArrayList<Attendance> attendanceArrayList) throws JSONException {
JSONObject object = new JSONObject();
JSONArray jsonArray = new JSONArray();
for(int i = 0;i<attendanceArrayList.size();i++){
JSONObject objId = new JSONObject();
JSONObject objAtt = new JSONObject();
objAtt.put("attendance_user_status",attendanceArrayList.get(i).getValue());
objId.put(attendanceArrayList.get(i).getId(),objAtt);
jsonArray.put(objId);
}
object.put("user",jsonArray);
return object.toString();
}
But using this code I'm getting this array, Not as I required.
{
"user": [
{
"1": {
"attendance_user_status": "2"
}
},
{
"2": {
"attendance_user_status": "1"
}
},
{
"3": {
"attendance_user_status": "1"
}
},
{
"4": {
"attendance_user_status": "1"
}
}
]
}
I want to append json object but not by json array.
You never initilize json any other than String json = "";, so an empty string will be returned.
You have to get the string from your json object and set it to json.
Do the following at the end of your method:
json = objId.toString();
return json;
Try like this:
public String jsonCreator(ArrayList<Attendance> attendanceArrayList) throws JSONException {
JSONArray jsonArray = new JSONArray();
for(int i = 0;i<attendanceArrayList.size();i++){
JSONObject objId = new JSONObject();
JSONObject objAtt = new JSONObject();
objAtt.put("attendance_user_status",attendanceArrayList.get(i).getValue());
objId.put(attendanceArrayList.get(i).getId(),objAtt);
jsonArray.put(objId);
}
return jsonArray.toString();
}

After Getting object/array from json, how can i shuffle it (Randomize)

I got the json data using this
``
private void loadQuestions() throws Exception {
try {
InputStream questions = this.getBaseContext().getResources()
.openRawResource(R.raw.questions);
bReader = new BufferedReader(new InputStreamReader(questions));
StringBuilder quesString = new StringBuilder();
String aJsonLine = null;
while ((aJsonLine = bReader.readLine()) != null) {
quesString.append(aJsonLine);
}
Log.d(this.getClass().toString(), quesString.toString());
JSONObject quesObj = new JSONObject(quesString.toString());
quesList = quesObj.getJSONArray("Questions");
Log.d(this.getClass().getName(),
"Num Questions " + quesList.length());
} catch (Exception e){
} finally {
try {
bReader.close();
} catch (Exception e) {
Log.e("", e.getMessage().toString(), e.getCause());
}
}
}
public static JSONArray getQuesList() {
return quesList;
}
``
Here is the json data.
``
{
"Questions": [
{
"Question": "Which animal is Carnivorous?",
"CorrectAnswer": 1,
"Answers": [
{
"Answer": "Cow"
},
{
"Answer": "Lion"
},
{
"Answer": "Goat"
},
{
"Answer": "Elephant"
}
]
},
{
"Question": "Humans need",
"CorrectAnswer": 0,
"Answers": [
{
"Answer": "Oxygen"
},
{
"Answer": "Nitrogen"
},
{
"Answer": "CarbonDioxide"
},
{
"Answer": "Hydrogen"
}
]
},
{
"Question": "Choose the Amphibian ",
"CorrectAnswer": 0,
"Answers": [
{
"Answer": "Frog"
},
{
"Answer": "Owl"
},
{
"Answer": "Goat"
},
{
"Answer": "Fox"
}
]
},
{
"Question": "---- is part of Earth`s Atmosphere.",
"CorrectAnswer": 1,
"Answers": [
{
"Answer": "Unisphere"
},
{
"Answer": "Troposphere"
},
{
"Answer": "Oxysphere"
},
{
"Answer": "Carbosphere"
}
]
},
]
}
After getting the json data
All I need now is to randomize it.
Help a brother please, I have tried everything but nothing is working
Thanks in advance
After
quesList = quesObj.getJSONArray("Questions"); // Right place to shuffle PeterOla,add this to randomize questions list:
List<JSONObject> questionsList = new ArrayList<JSONObject>(quesList.length());
for(int i=0,size=quesList.length();i<size;++i){
try {
questionsList.add(quesList.getJSONObject(i));
} catch (JSONException e) {
e.printStackTrace();
}
}
long seed = System.nanoTime();
Collections.shuffle(questionsList, new Random(seed));
Put values into a list, then you can shuffle it easily. Use this:
ArrayList<String> listdata = new ArrayList<String>();
JSONArray jArray = (JSONArray)jsonObject;
if (jArray != null) {
for (int i=0;i<jArray.length();i++){
listdata.add(jArray.get(i).toString());
}
}
Collections.shuffle(listdata);
try {
JSONObject jsonObject = new JSONObject(response);
String current_page = jsonObject.optString("current_page");
NextPageUrl = jsonObject.optString("next_page_url");
if (current_page.equals("1")){
lifeHomeModels.clear();
JSONArray data = jsonObject.getJSONArray("data");
for (int i =0;i<data.length();i++){
JSONObject jsonObject1 = data.getJSONObject(i);
String id = jsonObject1.optString("id");
String post_user_id = jsonObject1.optString("user_id");
String post_id = jsonObject1.optString("post_id");
String post_details = jsonObject1.optString("post_details");
}
Family_HomeModel inputModel = new Family_HomeModel();
inputModel.setId(id);
inputModel.setPost_user_id(post_user_id);
inputModel.setPost_id(post_id);
inputModel.setPost_details(post_details);
lifeHomeModels.add(inputModel);
}
long seed = System.nanoTime();
Collections.shuffle(lifeHomeModels, new Random(seed));
}
lifeHomeAdapter.notifyDataSetChanged();
}
catch (JSONException e) {
e.printStackTrace();
}

Converting JSON to model object Android

I'm new to using JSON in Android and have been running into a few problems creating a model object from the JSON. If anyone knows of any good tutorials or resources that would be good to look into for more details I'd really appreciate them. I've been looking at the tutorial on Vogella and in the Bignerdranch Android book thus far.
I'm able to pull in the JSON and create a JSONobject, however my surveys aren't saving.
Here's the JSON I'm trying to parse:
[
{
"title": "Pepsi or Coke?",
"id": 1,
"questions": [
{
"id": 1,
"title": "Which pop do you prefer?",
"single_response": true,
"answers": [
{
"title": "Pepsi",
"id": 1
},
{
"title": "Coke",
"id": 2
},
{
"title": "Mountain Dew",
"id": 3
}
]
},
{
"id": 2,
"title": "What's your age?",
"single_response": true,
"answers": [
{
"title": "18-24",
"id": 4
},
{
"title": "25-34",
"id": 5
},
{
"title": "35-50",
"id": 6
},
{
"title": "50+",
"id": 7
}
]
},
{
"id": 3,
"title": "What's your political association?",
"single_response": true,
"answers": [
{
"title": "Republican",
"id": 8
},
{
"title": "Democrat",
"id": 9
}
]
}
]
}
]
I'm retrieving the json like this:
byte[] getUrlBytes(String urlSpec) throws IOException {
URL url = new URL(urlSpec);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
try {
ByteArrayOutputStream out = new ByteArrayOutputStream();
InputStream in = connection.getInputStream();
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
return null;
}
int bytesRead = 0;
byte[] buffer = new byte[1024];
while ((bytesRead = in.read(buffer)) > 0) {
out.write(buffer, 0, bytesRead);
}
out.close();
return out.toByteArray();
} finally {
connection.disconnect();
}
}
public String getUrl(String urlSpec) throws IOException {
return new String(getUrlBytes(urlSpec));
}
And here's where I parse it:
public ArrayList<Survey> getSurveys(String apiKey) throws JSONException {
ArrayList<Survey> surveys = new ArrayList<Survey>();
try {
String url = Uri.parse(ENDPOINT).buildUpon().appendQueryParameter("auth_token", apiKey).build().toString();
String jsonString = getUrl(url);
Log.i(TAG, "Received json string: " + jsonString);
try {
JSONArray array = new JSONArray(jsonString);
for (int i = 0; i < array.length(); i ++) {
JSONObject object = array.getJSONObject(i);
Log.i(TAG, "Object is: " + object.toString());
}
for (int i = 0; i < array.length(); i++) {
Survey survey = new Survey(array.getJSONObject(i));
surveys.add(survey);
Log.i(TAG, "Survey is: " + survey.toString());
}
} catch (Exception e) {
Log.e(TAG, "Survey didn't save");
}
} catch (IOException ioe) {
Log.e(TAG, "Failed to retrieve surveys: " + ioe);
}
return surveys;
}
I'm assuming that the issue is in my create survey method itself since the JSONobjects are created correctly, but the surveys aren't saving. Any idea where I'm going wrong?
public Survey(JSONObject json) throws JSONException {
mId = UUID.fromString(json.getString("id"));
if (json.has("title")) {
mTitle = json.getString("title");
}
}
As always any help is very much appreciated!
Turns out the problem was that I was trying to convert the int id that was getting sent in JSON to a UUID.
As long as the data types match up the items are created correctly.

Nested JSON arrays

I am parsing some JSON that has arrays within arrays, and I just cant seem to get the data of the arrays within the first array.
My JSON looks like this (I cut it off in the end so it wasn't that long):
{"TrackingInformationResponse": {
"shipments": [
{
"shipmentId": "03015035146308",
"uri": "\/ntt-service-rest\/api\/shipment\/03015035146308\/0",
"assessedNumberOfItems": 1,
"deliveryDate": "2013-05-13T11:47:00",
"estimatedTimeOfArrival": "2013-05-13T16:00:00",
"service": {
"code": "88",
"name": "DPD"
},
"consignor": {
"name": "Webhallen Danmark ApS",
"address": {
"street1": "Elsa Brändströms Gata 52",
"city": "HÄGERSTEN",
"countryCode": "SWE",
"country": "Sverige",
"postCode": "12952"
}
},
"consignee": {
"name": "Lene Bjerre Kontor & IT Service",
"address": {
"street1": "Lene Bjerre",
"street2": "Ørbækvej 8, Hoven",
"city": "TARM",
"countryCode": "???",
"postCode": "6880"
}
},
"statusText": {
"header": "Forsendelsen er udleveret",
"body": "Forsendelsen blev leveret 13-05-2013 kl. 11:47"
},
"status": "DELIVERED",
"totalWeight": {
"value": "0.55",
"unit": "kg"
},
"totalVolume": {
"value": "0.005",
"unit": "m3"
},
"items": [
{
"itemId": "03015035146308",
"dropOffDate": "2013-05-08T17:18:00",
"deliveryDate": "2013-05-13T11:47:00",
"status": "DELIVERED",
"statusText": {
"header": "Forsendelsen er udleveret til modtageren",
"body": "Forsendelsen blev udleveret 13-05-2013 kl. 11:47"
},
I can get the content of the "shipments" array just fine, but I have no idea how to get the contents of the "items" array. My code looks like this:
try {
JSONObject jsonObject = new JSONObject(result);
JSONObject TrackingInformationResponse = new JSONObject(jsonObject.getString("TrackingInformationResponse"));
JSONArray shipments = new JSONArray(TrackingInformationResponse.getString("shipments"));
for (int i = 0; i < shipments.length(); i++) {
JSONObject JSONitems = shipments.getJSONObject(i);
String shipmentId = JSONitems.getString("shipmentId");
//do stuff
}
} catch (Exception e) {
Log.d("ReadWeatherJSONFeedTask", e.getLocalizedMessage());
}
How would I do the same with the "items" array as I did with the "shipments" array?
You have to get the items array from inside the Shipment array, like you did the shipments, then iterate through that, like you did the shipments.
It might look something like:
JSONObject jsonObject = new JSONObject(result);
JSONObject TrackingInformationResponse = new JSONObject(jsonObject.getString("TrackingInformationResponse"));
JSONArray shipments = new JSONArray(TrackingInformationResponse.getString("shipments"));
for (int i = 0; i < shipments.length(); i++) {
JSONObject JSONitems = shipments.getJSONObject(i);
String shipmentId = JSONitems.getString("shipmentId");
JSONArray items = new JSONArray(JSONitems.getString("items");
//get items stuff
//do stuff
}
} catch (Exception e) {
Log.d("ReadWeatherJSONFeedTask", e.getLocalizedMessage());
}
items is a JSON Array located inside the shipments array, so you need to get the items array within the shipments, maybe like this :
for (int i = 0; i < shipments.length(); i++) {
JSONObject JSONitems = shipments.getJSONObject(i);
String shipmentId = JSONitems.getString("shipmentId");
JSONArray items = new JSONArray(JSONitems.getString("items"));
//iterate over items
}
Hope this helps, Good luck
Try bellow code:
JSONObject jObject = new JSONObject(yourJSONString);
JSONObject trackInfo = jObject.getJSONObject("TrackingInformationResponse");
JSONArray shipMents = trackInfo.getJSONArray("shipments");
JSONArray items = shipMents.getJSONArray("items");

Categories

Resources