Convert JSON key value pairs into JSON Array Android - android

I have an array of key-value pairs like this:
{
"320x240":"http:\/\/static.example.com\/media\/content\/2012\/Jul\/mercedes-benz-a-klasse-red-t_320x240.jpg",
"300x225":"http:\/\/static.zigwheels.com\/media\/content\/2012\/Jul\/mercedes-benz-a-klasse-red-t_300x225.jpg",
"200x150":"http:\/\/static.zigwheels.com\/media\/content\/2012\/Jul\/mercedes-benz-a-klasse-red-t_200x150.jpg"
}
What I'm doing currently is this:
try {
images_object = new JSONObject(imageList);//imageList is a String of the above array //of key value pairs
Iterator<?> keys = images_object.keys();
String string_images = "";
if(keys.hasNext()) {
String key = (String)keys.next();
String value = (String)images_object.get(key);
string_images = "[" + value;
}
while( keys.hasNext() ){
String key = (String)keys.next();
String value = (String)images_object.get(key);
string_images = string_images + "," + value;
}
string_images = string_images + "]";
String encoded_json_string = JSONObject.quote(string_images);
images = new JSONArray(encoded_json_string);//images is of type JSONArray but it is null
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
But, images, is NULL. Why's that? What am I missing?

you can get all values from current JSONObject in JSONArray as:
Iterator<String> keys = images_object.keys();
JSONArray images = new JSONArray();
while( keys.hasNext() ){
String key = keys.next();
String value = images_object.optString(key);
//add value to JSONArray from JSONObject
images.put(value);
}
EDIT
Simplified solution is get the keys with images_object.names() and you can pass JSONArray of keys to toJSONArray method to get the value with respect to keys in JSONArray
JSONArray keys=images_object.names();
JSONArray values=images_object.toJSONArray(keys);
To Summing up simplified solution is:
JSONArray images=images_object.toJSONArray(images_object.names());

Related

How to convert JSONObject to Hashmap?

String jsonString = "{"name":"kd","isMe":"yes","time":"10:12 AM"},{"name":"you","isMe":"no","time":"10:12 AM"}";
JSONObject jValueObject = new JSONObject(jsonString);
Iterator<?> values = jValueObject.keys();
while(values.hasNext()){
String final_key = (String)values.next();
String final_value = jValueObject.getString(final_key);
if (final_value != "")
map.put(final_key, final_value);
if (!final_key.equals("")) {
sbkeys.append(final_key).append(',');
}
}
Log.e("Final_Map", String.valueOf(map));
itemList = sbkeys.toString();
Output : {name=kd,isMe=yes,time=10:12 AM}
Try this code:
HashMap map = new HashMap<String, String>();
Iterator<?> values = jValueObject.keys();
while(values.hasNext()) {
String final_key = (String)values.next();
String final_value = jValueObject.optString(final_key, "");
if (!final_value.equals(""))
map.put(final_key, final_value);
}
for (k : map.keySet()) {
Log.d("Final_Map", "map[" + key + "] : " + map.get(k));
}
this is a duplicate question,
please check these answers
Convert JSONObject to Map
use Jackson(http://jackson.codehaus.org/) from http://json.org/
HashMap<String,Object> result =
new ObjectMapper().readValue(<JSON_OBJECT>, HashMap.class);
or
You can use Gson() (com.google.gson) library if you find any difficulty using Jackson.
HashMap<String, Object> yourHashMap = new Gson().fromJson(yourJsonObject.toString(), HashMap.class);
First off, if its a json array that you need in the string then wrap your string in square brackets. (I'd expect you've escaped the double quotes as well).
String jsonString = "[{\"name\":\"kd\",\"isMe\":\"yes\",\"time\":\"10:12 AM\"},{\"name\":\"you\",\"isMe\":\"no\",\"time\":\"10:12 AM\"}]";
Now its a JSONArray and not a JSONObject. So to get a list of Maps,
JSONArray jValueArray = new JSONArray(jsonString);
List<Object> listOfMaps = jValueArray.toList();
System.out.println(listOfMaps);
Prints:
[{isMe=yes, name=kd, time=10:12 AM}, {isMe=no, name=you, time=10:12 AM}]
JSONObject jObject = new JSONObject(jsonString);
Iterator<?> keys = jObject.keys();
while (keys.hasNext()) {
map = new HashMap<String, String>();
sbkeys = new StringBuilder();
String key = (String) keys.next();
String value = jObject.getString(key);
try{
JSONObject jValueObject = new JSONObject(value);
Iterator<?> values = jValueObject.keys();
while (values.hasNext()) {
String final_key = (String) values.next();
String final_value = jValueObject.getString(final_key);
if (!final_value.equalsIgnoreCase("")) {
map.put(final_key, final_value);
sbkeys.append(final_key).append(',');
}
}
}catch (Exception e){
e.fillInStackTrace();
}
try {
//// Your Code..
} catch (Exception e) {
errorCode = "1";
}
}

Convert JSONArray string value into int value

I need to convert the value from key "Quantity" into a int.
Basically I have this:
[{"Code":"NV","Quantity":"333"},{"Code":"NV","Quantity":"333"}]
Need to convert to this:
[{"Code":"NV","Quantity":333},{"Codigo":"NV","Quantity":333}]
How can I do it?
Assuming your json data in string and setting it in data string
String data = "[{\"Code\":\"NV\",\"Quantity\":\"333\"},{\"Code\":\"NV\",\"Quantity\":\"333\"}]";
try {
JSONArray jsonArray = new JSONArray(data);
Log.d(TAG, "Old JSONArray: " + jsonArray); // [{"Code":"NV","Quantity":"333"},{"Code":"NV","Quantity":"333"}]
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = (JSONObject) jsonArray.get(i);
int quantityValue = Integer.parseInt(jsonObject.getString("Quantity"));
jsonObject.put("Quantity", quantityValue);
}
Log.d(TAG, "New JSONArray: " + jsonArray); // [{"Code":"NV","Quantity":333},{"Code":"NV","Quantity":333}]
} catch (JSONException e) {
e.printStackTrace();
}
What I am doing here is just replacing old Quantity string value with int value by using Integer.parseInt()
Please try the following:
for(int i = 0; i < array.length(); i++){
JSONObject object = array.getJSONObject(i);
object.put("Quantity", Integer.parseInt(object.getString("Quantity")));
}
You will need to replace array with the name of your array.

Set json object's key in android

I have this json file:
[ { “dir radix”: [ {”dir1”:”dir”}, {”dir3”:”dir”},] },
{ “dir1”: [ {”dir11”:”dir”}, {”dir12”:”dir”}]},
{ “dir3”: []}
]
How can I set the key "dir radix" or the others?
I use this code to search the right key that I want to rename:
try {
parse = new JSONArray(temp);
//temp is the string returned by the reading of the file json
JSONObject obj = new JSONObject();
for (i = 0; i < parse.length() && flag == 0; i++) {
obj = parse.getJSONObject(i);
Iterator iterator = obj.keys();
while (iterator.hasNext() && flag == 0) {
String key = (String) iterator.next();
//elem is the selected item that I want to rename
if (elem.equals(key)) {
flag = 1;
//set json's key
}
}
}
writefile(parse.toString(),f);
} catch (Exception e) {
e.printStackTrace();
}
There is no possibility to replace json object key, so maybe you can remove object and add new object with new key. Try that code
String newKey = "NEW_KEY";
String elem = "OLD_KEY";
String temp = "SRC_JSON";
int flag = 0;
JSONArray parse = new JSONArray(temp);
//temp is the string returned by the reading of the file json
JSONObject obj = null;
for (int i = 0; i < parse.length() && flag == 0; i++) {
obj = parse.getJSONObject(i);
Iterator iterator = obj.keys();
while (iterator.hasNext() && flag == 0) {
String key = (String) iterator.next();
//elem is the selected item that I want to rename
if (elem.equals(key)) {
flag = 1;
//set json's key
JSONArray array = obj.getJSONArray(key);
obj.remove(key);
obj.put(newKey, array);
}
}
}
JSONObject in java represents a mapping, so you can't easily change a key. You can, however, remove a value and re-add that value with a different key. Here's a convenience method that can help:
public static void changeKey(JSONObject object, String oldKey, String newKey) throws JSONException {
if (!object.has(oldKey)) {
// key doesn't exist, quit early
return;
}
Object oldData = object.get(oldKey);
object.remove(oldKey);
object.put(newKey, oldData);
}
And in your scenario, you no longer have to loop through the keys. You can simply call like this:
changeKey(obj, key, "new_key");

not getting the specific result json object and how to compare the two string's

i want to get only gender but it shows {"face":[{"gender": {"value": "Male"}}]}
i only want gender
please help me how it solve JSONArray jArray = rst.getJSONArray("face");
for (int i = 0; i < jArray.length(); i++) {
String gender=jArray.getJSONObject(i).getJSONObject("attribute").getString("gender");
String jsonText;
jsonText = gender;
textview2.setText("GENDER" + jsonText);
Check this code:-
Case 1:This code generate only one toast
String result = "{\"face\":[{\"gender\": {\"value\": \"Male\"}}]} ";
try {
JSONArray objJsonArray = new JSONObject(result).getJSONArray("face");
String gender = new JSONObject(objJsonArray.getJSONObject(0).getString("gender")).getString("value");
Toast.makeText(this, "Gender is==>" + gender, Toast.LENGTH_SHORT).show();
} catch (JSONException e) {
e.printStackTrace();
}
Case 2:-This code generate two toasts.
String result = "{\"face\":[{\"gender\": {\"value\": \"Male\"}},{\"gender\": {\"value\": \"Female\"}}]}";
try {
JSONArray objJsonArray = new JSONObject(result).getJSONArray("face");
for (int i = 0; i < objJsonArray.length(); i++) {
String gender = new JSONObject(objJsonArray.getJSONObject(i).getString("gender")).getString("value");
Toast.makeText(this, "Gender is==>" + gender, Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
Hope it solves your problem
Try this on the last line:
textview2.setText("GENDER" + jsonText.value);
On this line you are getting the entire array:
JSONArray jArray = rst.getJSONArray("face");<br>
A JSONArray is an Array of json objects.
The json object is a name value pair.
It looks like this:
jArray[{name:”John” , gender:”male”},
{name:”jane” , gender:”female”},
{name:”Mike” , gender:”male”}]<br>
This next line loops through the array that you have. Each time pulling a different json object:
1st time through = [{name:”John” , gender:”male”}
2nd time through = {name:”jane” , gender:”female”}
3rd time through = {name:”Mike” , gender:”male”}
for (int i = 0; i < jArray.length(); i++) { String
On the first look i = 0
This following line is saying: retrieve the json data where the name is gender.
This returns {gender:”male”} “gender” being the name, “male” being the value.
gender=jArray.getJSONObject(i).getJSONObject("attribute").getString("gender").value; <br>
String jsonText; jsonText = gender;
textview2.setText("GENDER" + jsonText);
I believe there are other more efficient ways to handle this same code, but I hope this helps none the less.
try {
JSONObject jsonObject = new JSONObject(string);
JSONArray jsonArray = jsonObject.getJSONArray("face");
for(int i=0; i<jsonArray.length(); i++){
String gender = jsonArray.getJSONObject(i).getJSONObject("gender").getString("value");
}
} catch (JSONException e) {
e.printStackTrace();
}
if you have JsonArray length 1 then no need of for loop just replace i with 0

Parsing json array from the JSON object in Android

I am trying to parse a JSON array from a string which I receive from the server.
Example of the array is
{"data":[{"id":703,"status":0,"number":"123456","name":"Art"}]}
I am trying to parse that using the below code which is giving me Classcast Exception which shows JSonArray can not be cast to List
JSONObject o = new JSONObject(result.toString());
JSONArray slideContent = (JSONArray) o.get("data");
Iterator i = ((List<NameValuePair>) slideContent).iterator();
while (i.hasNext()) {
JSONObject slide = (JSONObject) i.next();
int title = (Integer)slide.get("id");
String Status = (String)slide.get("status");
String name = (String)slide.get("name");
String number = (String)slide.get("number");
Log.v("ONMESSAGE", title + " " + Status + " " + name + " " + number);
// System.out.println(title);
}
What should be the correct way of parsing it?
It makes sense as a JSONArray cannot be cast to a List<>, nor does it have an iterator.
JSONArray has a length() property which returns its length, and has several get(int index) methods which allow you to retrieve the element in that position.
So, considering all these, you may wish to write something like this:
JSONObject o = new JSONObject(result.toString());
JSONArray slideContent = o.getJSONArray("data");
for(int i = 0 ; i < slideContent.length() ; i++) {
int title = slideContent.getInt("id");
String Status = slideContent.getString("status");
// Get your other values here
}
you should do like this:
JSONObject o = new JSONObject(result.toString());
JSONArray array = jsonObject.getJSONArray("data");
JSONObject jtemp ;
ArrayList<MData/*a sample class to store data details*/> dataArray= new ArrayList<MData>();
MData mData;
for(int i=0;i<array.length();i++)
{
mData = new MData();
jtemp = array.getJSONObject(i); //get i record of your array
//do some thing with this like
String id = jtemp.getString("id");
mData.setId(Integer.parseInt(id));
///and other details
dataArray.put(mData);
}
and MData.class
class MData{
private int id;
/....
public void setId(int id){
this.id = id;
}
//.....
}

Categories

Resources