Iterate through Java jsonObjects without array included - android

My problem is that this will create 3 new instances of DailyJobObjects with the same values as object number one (01, Bill, 50). And it's logical that it would do so, so how can I iterate through my jsonObject so I can separate the three objects? I have looked this up tirelessly but everything thing I have seen has and array included in the jsonData which would make things easier but this response Body is coming straight from a database - no arrays, just back to back objects. Iterating only gives me keys which I already did in a separate method to give me one half of my map. Now I need the values. You don't have to give me an answer, you can (I rather) point to something I'm missing. Thanks!
{"id":"01","name":"Bill","salary":"50"},
{"id":"02","name":"James","salary":"60"},
{"id":"03","name":"Ethan","salary":"70"}
JSONObject fields = new JSONObject(jsonData);
mObjectArray = new DailyJobObjectArray[fields.length()];
for(int i=0; i< fields.length(); i++) {
DailyJobObject mObject = new DailyJobObject();
mObject.setName(fields.getString("name"));
mObject.setSalary(fields.getString("salary"));
mObjectArray[i] = mObject;
}
return mObjectArray;

As #Selvin has mentioned, your json is not valid. Either get proper json from the database or parse it in a non-standard way. I would suggest getting a proper json array from the DB.
String[] splitString = jsondata.split("[^a-zA-Z \\{\\}]+(?![^\\{]*\\})");
for ( String s : splitString) {
try {
JSONObject field = new JSONObject(s);
String name = field.getString("name");
String id = field.getString("id");
} catch (JSONException e) {
e.printStackTrace();
}
}
I also agree that your mObject(...) does not make sense at all
Maybe you're looking for something like this
mObject.setName(name)

Related

How to retrieve an multiple records using JSONARRAY in Android

Now currently i am getting only updated data of same user by passing id through url.
using this below code....
try {
JSONArray jr = new JSONArray(jsonStr);
for(i=0;i<3;i++) {
JSONObject jb = (JSONObject) jr.getJSONObject(i);
value = jb.getString("amount");
tran_count = jb.getString("tran_count");
debitstr = jb.getString("debit");
creditstr = jb.getString("credit");
pointsmodestr = jb.getString("points_mode");
updatecpa = value;
}
}catch(Exception e)
{
e.printStackTrace();
}
But i need to retrieve multiple data of same user id.
For example:
Now for above code it is only displaying updated data of same user.
it displays only one array.
[{"id":"46097","user_id":"1066","email":"rahul#gmail.com","rolename":"12","account_no":"3445557752334556","debit":"0","credit":"0","amount":"0","points_mode":"wallet","challan":"","used":"yes","paid_to":"00","pay_type":"0","tranx_id":"One time Sponsorship Charges Deduction","active":"0","created_at":"1497008167","modified_at":"1497008167","tran_count":"3"}]
How to display multiple JSONARRAY in android of same user
example:
1st array of user id=1066 [{"id":"46097","user_id":"1066","email":"rahul#gmail.com","rolename":"12","account_no":"3445557752334556","debit":"0","credit":"0","amount":"0","points_mode":"wallet","challan":"","used":"yes","paid_to":"00","pay_type":"0","tranx_id":"One time Sponsorship Charges Deduction","active":"0","created_at":"1497008167","modified_at":"1497008167","tran_count":"3"}]
2nd Array of user id=1066
[{"id":"27098","user_id":"1066","email":"rahul#gmail.com","rolename":"12","account_no":"3445557752334556","debit":"0","credit":"0","amount":"0","points_mode":"wallet","challan":"","used":"no","paid_to":"00","pay_type":"2","tranx_id":"Referral offer","active":"0","created_at":"1492671459","modified_at":"1492671459","tran_count":"2"}]
In code, only value is getting added to list, why?
Hope jsonStr should be proper and on
JSONArray jr = new JSONArray(jsonStr);
code will get below kind of jsonArray. If it is the case, it will be retrieved perfectly. and it will be in this kind of format
`[{"id":"46097","user_id":"1066","email":"rahul#gmail.com","rolename":"12","account_no":"3445557752334556","debit":"0","credit":"0","amount":"0","points_mode":"wallet","challan":"","used":"yes","paid_to":"00","pay_type":"0","tranx_id":"One` time Sponsorship Charges Deduction","active":"0","created_at":"1497008167","modified_at":"1497008167","tran_count":"3"},
{"id":"27098","user_id":"1066","email":"rahul#gmail.com","rolename":"12","account_no":"3445557752334556","debit":"0","credit":"0","amount":"0","points_mode":"wallet","challan":"","used":"no","paid_to":"00","pay_type":"2","tranx_id":"Referral offer","active":"0","created_at":"1492671459","modified_at":"1492671459","tran_count":"2"},<another value>]
In your code, instead of
for(i=0;i<3;i++) {
please change to
for(i=0;i<jr.length();i++) { //as till the last jsonarray it will traverse.
if things are not working, mostly jsonStr must be wrong
Hope that helps

Android Not Sure How To Refer To Value In JSON File (JSON Parsing)

Example JSON Page
http://maps.googleapis.com/maps/api/geocode/json?latlng=51.155455,-0.165058&sensor=true
#SuppressLint("NewApi")
public void readAndParseJSON(String in) {
try {
JSONObject reader = new JSONObject(in);
// This works and returns address
JSONArray resultArry = reader.getJSONArray("results");
String Address = resultArry.getJSONObject(1).getString("formatted_address").toString();
Log.e("Address", Address);
// Trying to get PostCode on code below - this is not working (log says no value at address components)
JSONArray postCodeArray = reader.getJSONArray("address_components");
String postCode = postCodeArray.getJSONObject(1).getString("long_name").toString();
Log.e("PostCode", postCode );
This code returns the address correctly. How can I get the post code long_name which is inside address_components?
Solution
I had to get each array, and then get the post code value.
I am using the value 7, as that is the JSONObject that has the postcode stored in the "long_name" field.
JSONObject readerJsonObject = new JSONObject(in);
readerJsonObject.getJSONArray("results");
JSONArray resultsJsonArray = readerJsonObject.getJSONArray("results");
JSONArray postCodeJsonArray = resultsJsonArray.getJSONObject(0).getJSONArray("address_components");
String postCodeString = postCodeJsonArray.getJSONObject(7).getString("long_name").toString();
Log.e("TAG", postCodeString);
Hope that helps.
reader.getJSONObject(1).getJSONArray("address_components");
Your problem is that results is a JSONArray that contains a child JSONObject composed of several children: "address_components", "formatted_address", "geometry", and "types". The result array actually contains many of these such objects, but let's focus on just the first child for now.
Look carefully at your code. With this line:
JSONArray resultArry = reader.getJSONArray("results");
You are getting the entire results. Later on, you then call the same method again:
JSONArray postCodeArray = reader.getJSONArray("address_components");
But you're asking for an "address_components" from the reader, where I do not expect you'll find anything (having already read the entire result before.) You should instead be working with the JSONArray you already got before, since it already contains the entire result.
Try something like:
JSONObject addressComponents = resultArry.getJSONObject(1).getJSONObject("address_components");
String postCode = addressComponents.getString("long_name");
Note: I don't know why you're singling out JSONObject #1 (as opposed to 0, which is the first, or any other one of them) and I also am not sure why you named the String postCode. So if I've misunderstood your intention, I apologize.
Is difficult to find the error... because all looks well. The problem maybe can exist when you make the json.put("address_components", something);
So my advice is put a breakpoint at this line
JSONArray postCodeArray = reader.getJSONArray("address_components");
o display the json in logcat
Log.d("Simple", reader.toString());
Then Paste your json in this web page to view more pretty
http://jsonviewer.stack.hu/
and check if all keys are stored well.
Solution
Need to get each array, and then get the post code value. The value 7 is used, as that is the JSONObject that has the postcode stored in the "long_name" field.
JSONObject readerJsonObject = new JSONObject(in);
readerJsonObject.getJSONArray("results");
JSONArray resultsJsonArray = readerJsonObject.getJSONArray("results");
JSONArray postCodeJsonArray = resultsJsonArray.getJSONObject(0).getJSONArray("address_components");
String postCodeString = postCodeJsonArray.getJSONObject(7).getString("long_name").toString();
Log.e("TAG", postCodeString);
Hope that helps.

Json object to json array Java (Android)

It's been a while and i'm trying to ignore some frustrating issue i'm having with json things in java, i'm new to this and read alot however, parsing json in javascript or php was alot better (or easier i dunno) but now in java i cannot convert a jsonobject to jsonarray if it doesn't have a parent, cuz it uses .getJsonArray('array)
BUT what IF i have this :
{"49588":"1.4 TB","49589":"1.4 TB MultiAir","49590":"1.4 TB MultiAir TCT","49591":"1.6L MultiJet","49592":"1750 Tbi","49593":"2.0L MultiJet","49594":"2.0L MultiJet TCT"}
i'm not succeeding in anyway to convert it to array
what i want is to convert this JSONObject to JSONArray loop within its items and add them to a Spinner, now that's the first issue, the second question is: if i convert this to JSONArray how can i add the ID, Text to the spinner? just like the HTML Select tag
<option value="0">Item 1</option>
so it's an issue and a question hope someone can find the solution for this jsonarray thing, without modifying the json output from the website, knowing that if i modify and add a parent to this json, the JSONArray will work. but i want to find the solution for that.
Nothing special i have in the code:
Just a AsynTask Response, a log which is showing the json output i put at the beginning of this question
Log.d("response", "res " + response);
// This will work
jsonCarsTrim = new JSONObject(response);
// This won't work
JSONArray jdata = new JSONArray(response);
Thanks !
How about this:
JSONObject json = new JSONObject(yourObject);
Iterator itr = json.keys();
ArrayList<CharSequence> entries = new ArrayList<CharSequence>();
ArrayList<Integer> links = new ArrayList<Integer>();
int i = 0;
while(itr.hasNext()) {
String key = itr.next().toString();
links.add(i,Integer.parseInt(key));
entries.add(i, (CharSequence) json.getString(key)); //for example
i++;
}
//this is the activity
entriesAdapter = new ArrayAdapter<CharSequence>(this,
R.layout.support_simple_spinner_dropdown_item, entries);
//spinner is the spinner the data is added too
spinner.setAdapter(entriesAdapter);
this should work (works for me), you may have to modify the code.
The way shown, i am adding all entries of the json object into a Spinner, where my json key is the index value and the linked String value of the json object will be shown as Spinner entry (title) in my activity.
Now when an Item is selected, fetch the SelectedItemPosition and you can look it up in the "links" array list, to get the real value.
I'm not sure if this is thing you want but give it a try. There is tutorial to convert the Json to Map. After you convert it, you can iterate through the map.
http://www.mkyong.com/java/how-to-convert-java-map-to-from-json-jackson/
What you have is a JSON object type, not an array type. To iterate you can get the Iterator from the keys method.

How is this JSON string supposed to be parsed to get the different fields

I have this JSON string that I am recieving after I make a purchase from the playstore and I am apparently missing something in my code when I am trying to parse it.
PurchaseInfo:{"orderId":"12999763165555505758.1317333586444405",
"packageName":"com.mypkgname.myapp",
"productId":"monthly_purchase_01",
"purchaseTime":1357456489000,
"purchaseState":0,
"purchaseToken":"yrynypfkdncvhlxdbypysvwz.AO-J1OxFkndfqkClAqbbYAOApkMgTG4VX9Ef0uNP0FIs9-xGrXivkbx3FNMA2yNU12K_sbvRGFcknVBTfisI-uZawCXLGlMX4v4Zw8GFOmS0Q6PIbiITTGqn5h1QbEB4Rv84sXdUJHP3B_UQfujZN7ADi9bm_N4_iA"}
Here is the snippet of code I am using it to attempt the parsing
try {
JSONObject j1 = new JSONObject(tester1);
JSONArray mPurchInfo = j1.getJSONArray("PurchaseInfo");
int count = mPurchInfo.length();
final String[] purchInfo = new String[count];
JSONObject q1 = mPurchInfo.getJSONObject(0);
purchInfo[0] = q1.getString("orderId");
purchInfo[1] = q1.getString("packageName");
purchInfo[2] = q1.getString("productId");
purchInfo[3] = q1.getString("purchaseTime");
purchInfo[4] = q1.getString("purchaseState");
purchInfo[5] = q1.getString("purchaseToken");
orderID=purchInfo[0];
} catch (JSONException e) {
Log.e("Error","Yes");
}
I am catching the an error as I see this last log statement in my log but I am still trying to learn the parsing JSON Strings
I hope I am at least close
Ideally I would like to have Strings set to all the values in the JSON String
orderID = ??
packageName = ??
etc.
Thanks
I have this JSON string that I am recieving after I make a purchase from the playstore
If that's really what you get back, you need to contact them and tell them to fix their API; that string is not valid JSON. There are two problems with it:
A JSON document must have an object or array as the top-level item. The string as quoted is missing a { at the beginning and a } at the end.
All keys in JSON must be in double quotes. The first one, PurchaseInfo, is not.
Also, your code is doing this:
JSONArray mPurchInfo = j1.getJSONArray("PurchaseInfo");
...but if it were valid JSON, PurchaseInfo wouldn't be an array, it'd be an object.
Looking at it, if you remove the PurchaseInfo: at the beginning, it's valid. Once you've removed that, this line:
JSONObject j1 = new JSONObject(tester1);
...will give you an object from which you can query information:
String orderId = j1.getString("orderId");

android how to parse json

public void HelloWord {
for (int i = 0; i < 20; i++) {
Log.d("Great");
}
}
The code above doesn't work why?
I try to get value name
Does anybody know where is the problem?
org.json.JSONException: Value ...Content of link... at
org.json.JSON.typeMismatch at org.json.JSONArray.
I prefer to use the GSON library, as it is a fast and effective JSON parser. Once added to the project you will need to create classes to represent the data returned. You then can call a single function to create your objects for you:
gson.fromJson();
An exceptionally good article on the use of GSON can be found at http://www.javacodegeeks.com/2011/01/android-json-parsing-gson-tutorial.html - it even uses Twitter for the example.
I think that you are missing the way that JSON works. Anything in {} is an Object, while [] designates an array. So the root of the twitter feed is a JSONObject, NOT a JSONArray:
Try something more like this:
JSONObject obj = new JSONObject(mStringBuilder.toString());
JSONObject trends = obj.getJSONObject("trends");
JSONArray today = trends.getJSONArray("2012-04-10");
for (int i = 0; i < today.length(); i++) {
JSONObject tag = today.getJSONObject(i);
String name = tag.getString("name");
// do whatever with name
}
Much easier, and its clearer how it works. JSONObjects are dictionaries, with a simple mapping between keys and values - each Object ({}) can contain either more objects, or arrays ([]) which can contain either simple integers or more objects

Categories

Resources