Extracting JSON value, which is an array - java

I am trying to extract the value from a key-value pair in a JSONObect. Here is the structure:
{"key1 ":["dog","cat"],"key2":["house","boat"]}
So, I want to extract the values dog and cat, also values house and boat. I tried the following in Java:
//obj - has this JSON.
Iterator iter = obj.keys();
for (int i=0; i<len; i++){
String key = (String)iter.next();
System.out.println("Key is --> "+key); //This is correctly giving me the keys.
System.out.println("Value is --> "+clientDetails.getJSONArray(key)); //This is not working. I tried lots of other things but to no avail.
}
Could somebody please guide me here.
thanks,
Kay

You should use quick-json parser (https://code.google.com/p/quick-json/)
It can be used like this:
JsonParserFactory factory=JsonParserFactory.getInstance();
JSONParser parser=factory.newJsonParser();
Map jsonMap=parser.parseJson(jsonString);
Taken via : How to parse JSON in Java
This guy has explained it nicely.

I think you are using wrong variable named clientDetails here. you should use same JSON obj here.
The above code is working fine for me with same obj:
String json = "{\"key1 \":[\"dog\",\"cat\"],\"key2\":[\"house\",\"boat\"]}";
JSONObject obj=new JSONObject(json);
Iterator iter = obj.keys();
for (int i=0; i<obj.length(); i++){
String key = (String)iter.next();
System.out.println("Key is --> "+key);
System.out.println("Value is --> "+obj.getJSONArray(key));
}

Thank you for chipping in. I found the answer to my question. Here is how I extracted the value of a JSON which is key value pair, and the value is an array.
Iterator iter = obj.keys();
for (int i=0; i<len; i++){
String key = (String)iter.next();
System.out.println("Key is --> "+key);
String[] arr = (String[])clientDetails.get(key); //Here I am extracting the value which is an array, converting it to String array and then storing it in a variable of type String[]. Now I can loop through this "arr"
for (int m=0; m<arr.length;m++){
arr[]m // Can do whatever I want here!
}
Thank you guys!
-Kay

Related

JSON Array parsing where key is missing in the key-value pair

I am trying to parse a JSON Array which looks something like this
"data":["data1","data2","data3"]
If I write JSONArray arr = obj1.getJSONArray("data");, this will provide me with the JSON array but since the key name from key-value pair is missing, how will I retrieve "data1", "data2" and "data3"?
JSON arrays allows for non json children. In this case, the children are of String value:
for(int i=0;i<arr.length();i++) {
String value = arr.getString(i);
}
My syntax might be inaccurate
Assuming this is your JSON,
{"data":["data1","data2","data3"]}
Use the following to retrieve the array,
JSONArray arrJson = jsonData.getJSONArray("data");
String[] arr = new String[arrJson.length()];
for(int i = 0; i < arrJson.length(); i++) {
arr[i] = arrJson.getString(i);
}

How to put key/values into a HashMap from StringBuilder using loop? - Java

I'm using several techniques here, so it's hard to find help online.
I need to populate a HashMap<String, String> with values I take from part of a StringBuilder, then take the keys and add them into an ArrayList<String>, then print the list. But when I print, I get a list full of nulls. I don't know why, I thought it would print the values I got from the StringBuilder. It should print: Values taken from the hashmap keys: ABCDEFGHI. (The reason I used StringBuilder is because String is immutable, is this correct thinking too?)
Also, I figured using a loop to print the list is okay, since my keys are actually numbers.
I've never created a HashMap before, so maybe I'm missing something. Thanks for your help.
Here is my code:
// create HashMap from String
StringBuilder alphaNum = new StringBuilder("1A2B3C4D5E6F7G8H9I");
Map<String, String> myAlphaNum = new HashMap<String, String>(9);
// for loop puts key and values in map, taken from String
for (int i = 0; i < alphaNum.length();)
{
myAlphaNum.put(alphaNum.substring(i, ++i), alphaNum.substring(i, ++i));
}
if (myAlphaNum.containsKey(1))
System.out.println("Key is there.");
else
System.out.println("Key is null.");
// create ArrayList, add values to it using map keys
ArrayList<String> arrayList = new ArrayList<String>();
// for loop gets the "number" keys from HashMap to get the "letter" values
for (int j = 1; j <= myAlphaNum.size(); j++)
arrayList.add(myAlphaNum.get(j));
System.out.print("Values taken from the hashmap keys: ");
for (String list : arrayList)
System.out.print(list);
Console:
Key is null.
Values taken from the hashmap keys: nullnullnullnullnullnullnullnullnull
You are using containsKey/get with an Integer as parameter, while your map keys are defined as String. That's why you got null.
I would recommend to use a Map<Integer, String> myAlphaNum = new HashMap<Integer, String>(9); and in your loop myAlphaNum.put(Integer.parseInt(alphaNum.substring(i, ++i)), alphaNum.substring(i, ++i));. Then you'll get your desired output.
Also you could the ArrayList constructor that takes a Collection as parameter (or just sysout myAlphaNum.values()) directly.
// create ArrayList, add values to it using map keys
ArrayList<String> arrayList = new ArrayList<String>(myAlphaNum.values());
System.out.println(arrayList); //[A, B, C, D, E, F, G, H, I]
myAlphaNum has keys of type String, so passing an int to get (myAlphaNum.get(j)) will always return null.
There are several ways to iterate over the values (or keys or entries) of the map.
For example (assuming you only care about the values) :
for (String value : myAlphaNum.values())
arrayList.add(value);
// create HashMap from String
StringBuilder alphaNum = new StringBuilder("1A2B3C4D5E6F7G8H9I");
Map<String, String> myAlphaNum = new HashMap<String, String>(9);
// for loop puts key and values in map, taken from String
for (int i = 0; i < alphaNum.length();)
{
myAlphaNum.put(alphaNum.substring(i, ++i), alphaNum.substring(i, ++i));
}
System.out.println(myAlphaNum);
if (myAlphaNum.containsKey(1))
System.out.println("Key is there.");
else
System.out.println("Key is null.");
// create ArrayList, add values to it using map keys
ArrayList<String> arrayList = new ArrayList<String>();
// for loop gets the "number" keys from HashMap to get the "letter" values
for (int j = 1; j <= myAlphaNum.size(); j++)
arrayList.add(myAlphaNum.get(j+""));
System.out.print("Values taken from the hashmap keys: ");
for (String list : arrayList)
System.out.print(list);
You can try the above code. You have used string key bit while retriving Integer so it wont return anything.

get a Json value without string key - Java JSONObject

It' easy to get a value from JSON when you have the string key, but what if you have situation like that:
{
"images":["URL1"]
}
And array and no key inside? I use this code:
JSONArray imagesArr = propertiesjsonObject.getJSONArray("images");
for (int y=0; i<imagesArr.length(); y++)
{
JSONObject imagesJsonObject = imagesArr.getJSONObject(y);
String str_image_url = imagesJsonObject.get("HOW TO GET THE VALUES HERE?");
}
Propably it's ultra easy. Sorry to ask but I could not find proper example. PS. I use: import org.json.JSONArray;
import org.json.JSONObject;
PS2: For now there is only one element in array, but in future I suppouse there might be more.
Try with this:
ArrayList<String> urls = new ArrayList<String>();
JSONArray imagesArr = propertiesjsonObject.getJSONArray("images");
for (int i = 0; i < imagesArr.length(); i++) {
String str_image_url = imagesArr.getString(i);
urls.add(str_image_url);
}
urls is an array with all the url you got
Hope this helps
String str_image_url = imagesArr.getString(0);//you specify position in array here

Java hashmap from python dict command?

I have a weird problem that I don't fully understand how to solve. Could someone please give me some pointers on hashmaps?
I have a variable:
/servlet/charting?base_color=grey&chart_width=288&chart_height=160&chart_type=png&chart_style=manufund_pie&3DSet=true&chart_size=small&leg_on=left&static_xvalues=10.21,12.12,43.12,12.10,&static_labels=blue,red,green,purple"
I basically want 10.21,12.12,43.12,12.10 to be associated with blue,red,green,purple (in the order displayed)
In python I created a method that does this with:
def stripChart(name):
name = str(name)
name = urlparse.urlparse(name)
name = cgi.parse_qs(name.query)
name = dict(zip( name['static_labels'][0].split(','), name['static_xvalues'][0].split(',')))
Not sure how to do this in java. So far I have:
URL imgURL = new URL (imgTag);
String[] result = imgURL.getFile().split("&");
for (int x=0; x<result.length; x++)
System.out.println(result[x]);
This gives me:
chart_width=288
chart_height=160
chart_type=png
chart_style=manufund_pie
3DSet=true
chart_size=small
leg_on=left
static_xvalues=10.21,12.12,43.12,12.10,
static_labels=blue,red,green,purple,
At this point I'm confused how to link static_labels and static_xvalues values.
Thanks so much. Any pointers would be awesome.
You want to look at StringTokenizer
Something like this (assuming you stored the labels into the String 'static_labels' and the values in the String 'static_xvalues'):
HashMap<String, Double> colorMap = new HashMap<String, Double>();
StringTokenizer labelTok = new StringTokenizer(static_labels, ",");
StringTokenizer valuesTok = new StringTokenizer(static_xvalues, ",");
while(labelTok.hasMoreElements()){
assert(valuesTok.hasMoreElements());
colorMap.put(labelTok.nextElement(), Double.parseDouble(valuesTok.nextElement()));
}
Look at using java.util.HashMap. Let's say you have stored the static_xvalues and static_labels request parameters into corresponding string variables. Something like the following will create the mapping for you:
String[] vals = static_xvalues.split(",");
String[] labels = static_labels.split(",");
HashMap<String,String> map = new HashMap<String,String>();
for (int i=0; i < vals.length; ++i) {
map.put(labels[i], values[i]);
}
You do not say if the xvalues need to be stored as floats or not. If so, you will need to convert the vals array into a Float (or Double) array first, and modify the HashMap instantiation accordingly:
HashMap<String,Float> = new HashMap<String,Float>();

JSON Array iteration in Android/Java

I am building an android app that needs to download and synchronise with an online database, I am sending my query from the app to a php page which returns the relevant rows from a database in JSON format.
can someone please tell me the best way to iterate through a JSON array?
I receive an array of objects:
[{json object},{json object},{json object}]
What is the simplest piece of code I could use to access the JSONObjects in the array?
EDIT: now that I think of it the method I used to iterate the loop was:
for (String row: json){
id = row.getInt("id");
name = row.getString("name");
password = row.getString("password");
}
So I guess I had was somehow able to turn the returned Json into and iterable array. Any Ideas how I could achieve this?
I apologise for my vaguness but I had this working from an example I found on the web and have since been unable to find it.
I think this code is short and clear:
int id;
String name;
JSONArray array = new JSONArray(string_of_json_array);
for (int i = 0; i < array.length(); i++) {
JSONObject row = array.getJSONObject(i);
id = row.getInt("id");
name = row.getString("name");
}
Is that what you were looking for?
I have done it two different ways,
1.) make a Map
HashMap<String, String> applicationSettings = new HashMap<String,String>();
for(int i=0; i<settings.length(); i++){
String value = settings.getJSONObject(i).getString("value");
String name = settings.getJSONObject(i).getString("name");
applicationSettings.put(name, value);
}
2.) make a JSONArray of names
JSONArray names = json.names();
JSONArray values = json.toJSONArray(names);
for(int i=0; i<values.length(); i++){
if (names.getString(i).equals("description")){
setDescription(values.getString(i));
}
else if (names.getString(i).equals("expiryDate")){
String dateString = values.getString(i);
setExpiryDate(stringToDateHelper(dateString));
}
else if (names.getString(i).equals("id")){
setId(values.getLong(i));
}
else if (names.getString(i).equals("offerCode")){
setOfferCode(values.getString(i));
}
else if (names.getString(i).equals("startDate")){
String dateString = values.getString(i);
setStartDate(stringToDateHelper(dateString));
}
else if (names.getString(i).equals("title")){
setTitle(values.getString(i));
}
}
Unfortunately , JSONArray doesn't support foreach statements, like:
for(JSONObject someObj : someJsonArray) {
// do something about someObj
....
....
}
When I tried #vipw's suggestion, I was faced with this exception:
The method getJSONObject(int) is undefined for the type JSONArray
This worked for me instead:
int myJsonArraySize = myJsonArray.size();
for (int i = 0; i < myJsonArraySize; i++) {
JSONObject myJsonObject = (JSONObject) myJsonArray.get(i);
// Do whatever you have to do to myJsonObject...
}
If you're using the JSON.org Java implementation, which is open source, you can just make JSONArray implement the Iterable interface and add the following method to the class:
#Override
public Iterator iterator() {
return this.myArrayList.iterator();
}
This will make all instances of JSONArray iterable, meaning that the for (Object foo : bar) syntax will now work with it (note that foo has to be an Object, because JSONArrays do not have a declared type). All this works because the JSONArray class is backed by a simple ArrayList, which is already iterable. I imagine that other open source implementations would be just as easy to change.
On Arrays, look for:
JSONArray menuitemArray = popupObject.getJSONArray("menuitem");
You are using the same Cast object for every entry.
On each iteration you just changed the same object instead creating a new one.
This code should fix it:
JSONArray jCastArr = jObj.getJSONArray("abridged_cast");
ArrayList<Cast> castList= new ArrayList<Cast>();
for (int i=0; i < jCastArr.length(); i++) {
Cast person = new Cast(); // create a new object here
JSONObject jpersonObj = jCastArr.getJSONObject(i);
person.castId = (String) jpersonObj.getString("id");
person.castFullName = (String) jpersonObj.getString("name");
castList.add(person);
}
details.castList = castList;
While iterating over a JSON array (org.json.JSONArray, built into Android), watch out for null objects; for example, you may get "null" instead of a null string.
A check may look like:
s[i] = array.isNull(i) ? null : array.getString(i);

Categories