JSON Problem in android (objects disappear) - android

I'm trying to make a small app (an image gallery from images from the web, were the url's I get from the JSON file that I received). The context of JSON looks like that:
{"images":{
"yXVak":{
"image_hash":"yXVak",
"imgur_page":"http:\/\/imgur.com\/yXVak",
"original_image":"http:\/\/imgur.com\/yXVak.gif",
"large_thumbnail":"http:\/\/imgur.com\/yXVakl.gif",
"small_thumbnail":"http:\/\/imgur.com\/yXVaks.gif",
"message":"I didn't know they made you see THAT well.",
"source":" ",
"date_popular":"2011-07-18 18:45:05"},
.....
I have about 30 more objects that looks like "yXVak".
Now, the problem is, when I'm trying to parse the text, the program can't find the object "yXVak", the exception looks like that: org.json.JSONException: JSONObject["yXVak"] not found.
I parse the JSON file like that:
jObject = new JSONObject(jString);
JSONObject jImages = jObject.getJSONObject("images");
getImages(jImages);
getImages function looks like that:
JSONObject jHash = jImages.getJSONObject("yXVak") ;
String hash = jHash.getString("yXVak");
String page = jHash.getString("http:\\/\\/imgur.com\\/yXVak");
Image[] images = new Image[3];
images[0] = new Image(jHash.getString("original_image"), jHash.getString("http:\\/\\/imgur.com\\/yXVak.gif"));
images[1] = new Image(jHash.getString("large_thumbnail"), jHash.getString("http:\\/\\/imgur.com\\/yXVakl.gif"));
images[2] = new Image(jHash.getString("small_thumbnail"), jHash.getString("http:\\/\\/imgur.com\\/yXVaks.gif"));
String message = jHash.getString("I didn't know they made you see THAT well.");
String source = jHash.getString(" ");
String date = jHash.getString("2011-07-18 18:45:05");
listOfImages.add(new ImageHash(hash, page, images, message, source, date));
...
By debugging I found that the jString object looks right (the whole string that in the file), but the jImages object missing two first objects ("yXVak", and the second one that I didn't show here "6k9yE").
Can someone help me with that please, what did I do wrong?

I thing you should change this lines in your getImages function:-
JSONObject jHash = jImages.getJSONObject("yXVak");
//Changes in this lines.
String hash = jHash.getString("image_hash");
String page = jHash.getString("imgur_page");
// Rest of your code is same.
Please try this out.I think that it will solve your problem,

Related

Iterate through Java jsonObjects without array included

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)

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");

Extract text from String

I have one String and into this string I have a url between two characters # such as "Hello world #http://thisurl# my name is Pippo" I want to take the url (http://thisurl) between two #.
How can I do ? Thanks
String data[] = str.split("#"); //spilliting string and taking into array
ArrayList<String> urlList = new ArrayList<String>();
for (int i = 0; i < data.length; i++) {
if(data[i].contains("http://"))
urlList.add(data[i]); //if string contains "http://" it means it is url save int list.
}
now you can get all uls from urlList.get(i) method.
this urlList will give you all the urls available in the string. I dint applied any null or other check. Apply it and try. If want something else try modifying content and checks.
Try String.split(). You really should be trying to google these things first.
here is an example - http://www.java-examples.com/java-string-split-example
The split method divides a string into several strings and store them into an array using a delimiter which can be defined by you.
the second element in the resulting array will be your URL

Categories

Resources