Set json object's key in android - 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");

Related

json parse data set search condition is no working

I parse json data successfully , i can show it on my recyclerView.
it's my data source:
(had solved the issue)
I want to set a search condition about month > 5
I had set a String.equal("compareString"); before, it worked.
But when i set the month in this case, it's not working.
do i set something wrong? any help will be grateful.
private void showRoute(String route) {
try {
JSONObject jsonObject = new JSONObject(route);
String arrayData = jsonObject.getString("JsonData");
JSONArray jsonArray = new JSONArray(arrayData);
Log.d(TAG, "JSONArray" + ">>>>>>>>>>" + jsonArray);
for (int i = 467; i < jsonArray.length(); i++) {
int month=5;//set search condition, i want to show a list , it's month > 5
//here is my search condition
if (Integer.parseInt(jsonArray.getJSONObject(i).getString("STARTMONTH"))>=month) {
String EDUTITLE = jsonArray.getJSONObject(i).getString("EDUTITLE");
String STARTMONTH = jsonArray.getJSONObject(i).getString("STARTMONTH");
String STARTDAY = jsonArray.getJSONObject(i).getString("STARTDAY");
String STARTDATE = jsonArray.getJSONObject(i).getString("STARTDATE");
String SPONSER = jsonArray.getJSONObject(i).getString("SPONSER");
String EDUSCORE = jsonArray.getJSONObject(i).getString("EDUSCORE");
String EDUIN = jsonArray.getJSONObject(i).getString("EDUIN");
String HOLDER = jsonArray.getJSONObject(i).getString("HOLDER");
ActivityListItem listItem = new ActivityListItem(EDUTITLE, STARTMONTH, STARTDAY, STARTDATE, SPONSER, EDUSCORE, EDUIN, HOLDER);
arrayList.add(listItem);
}else {
recyclerView.setVisibility(View.GONE);
textForEmpty.setVisibility(View.VISIBLE);
}
//arrayListOrigin.add(listItem);
}
} catch (JSONException ex) {
ex.printStackTrace();
}
}
and another question , if my data is 467~500 , my list will show 467~500 from up to down , what if i want to let it shows 500~467 from up to down , what should i do is more correct ?
I try some code like: it show empty
String month="5";
if (month.equals(jsonArray.getJSONObject(i).getString("STARTMONTH"))) {
other code...
}
but if i try to compare EDUIN like this: it works...
String eduin="0";
if (eduin.equals(jsonArray.getJSONObject(i).getString("EDUIN"))) {
other code...
}
i don't get it now :(
The issue is your if condition may not be executed because of this line
String arrayData = jsonObject.getString("JsonData");
In your response "JsonData" is a JSONArray not a String .
Try this instead.
JSONObject jsonObject = new JSONObject(route);
JSONArray jsonArray = jsonObject.getJSONArray("JsonData") ;
for (int i = 467; i < jsonArray.length(); i++) {
//rest of your code
}
Now if you want to item from 500 to 467 reverse the loop
for(int i = jsonArray.length()-1; i >= 467; i--){
if(Integer.parseInt(jsonArray.getJSONObject(i).getString("STARTMONTH"))>=month){
// rest of the code..
}}
outside the loop hide recycleview like this
if (arrayList.size() == 0) {
//hide recycleview
recyclerView.setVisibility(View.GONE);
textForEmpty.setVisibility(View.VISIBLE);
}
Or
Much more easier way
ArrayList<Element> tempElements = new ArrayList<Element>(arrayList);
Collections.reverse(tempElements);

How to print a string if data is not available on server in android using json

Thank you guys.Finally i got the solution.If we want to check whether string is empty or null we must trim() the string.
String url="http://app name/Api/GetJobDetails/GetJobDetails?COMP_REQ_ID=" + title + "&StuEmail=" + e ; // this is the url
AQuery mAQuery = new AQuery(SecondActivity.this);
mAQuery.ajax(url, String.class, new AjaxCallback<String>() {
public Object dataSource;
#Override
public void callback(String url, String data, AjaxStatus status)
{
uper.callback(url, data, status);
if (null != data && status.getCode() != -101) {
String StringData = "" + data;
try {
JSONArray rootArray = new JSONArray(StringData);
int len = rootArray.length();
for (int i = 0; i < len; ++i) {
JSONObject json = rootArray.optJSONObject(i);
String Salary = json.optString("Req_From_Sal");
if (Salary == null || Salary.trim().equals("null") || Salary.trim().length() <= 0) {
b14.setText("Not Mentioned");
}
else
{
b14.setText(""+Salary);
}
}
}
}
});
Check you string if it is null or blank then print message what you want. For example:
if(StringData.length()==0){
//show message
}else{
JSONArray rootArray = new JSONArray(StringData);
int len = rootArray.length();
for (int i = 0; i < len; ++i) {
JSONObject json = rootArray.optJSONObject(i);
String Salary = json.optString("Req_From_Sal");
if (Salary == null)
b14.setText("NA"+Salary);
else
b14.setText(""+Salary)
}
}
MoreOver if you want to show specific message for specific user then ask for the success parameter. If success==1 go for you logic else if success ==0 then ask for message parameter as well parse it and show it to user
1.Check whether StringData is null or empty.
2.Check if rootArray.length()==0
Try this.
if(StringData!=null) {
JSONArray rootArray = new JSONArray(StringData);
for (int i = 0; i < rootArray.length(); ++i) {
JSONObject json = rootArray.optJSONObject(i);
String Job_Title = json.optString("Req_Title", "default_value");
String Designation = json.optString("Req_Designation_Role", "default_value");
String Salary = json.optString("Req_From_Sal", "Salary Not Mentioned");
b14.setText("" + Salary);
}
}else{
Log.d(TAG, "Invalid JSON Data");
b14.setText("Salary Not Mentioned");
}
USe TextUtils.isEmpty() to check for null and empty string.
Always add null check before getting any variable from object.
Modified code below:
JSONArray rootArray = new JSONArray(StringData);
if(rootArray!=null&&rootArray.length())
{
int len = rootArray.length();
for (int i = 0; i < len; ++i)
{
JSONObject json = rootArray.optJSONObject(i);
if (json != null) {
String Job_Title = json.optString("Req_Title");
String Designation = json.optString("Req_Designation_Role");
String Job_Type = json.optString("Req_Job_Type");
String Salary;
if (json.has("Req_From_Sal") && !TextUtils.isEmpty(json.getString("Req_From_Sal")) {
Salary = json.optString("Req_From_Sal");
} else {
Salary = "Not available";
}
b14.setText(Salary);
}
}
}
Thank you guys.Finally i got the solution. Here is edit code.To check the String is null or empty we should have to trim() the string.
Android side:-
String url="http://app name/Api/GetJobDetails/GetJobDetails?COMP_REQ_ID=" + title + "&StuEmail=" + e ; // this is the url
AQuery mAQuery = new AQuery(SecondActivity.this);
mAQuery.ajax(url, String.class, new AjaxCallback<String>() {
public Object dataSource;
#Override
public void callback(String url, String data, AjaxStatus status) {
uper.callback(url, data, status);
if (null != data && status.getCode() != -101) {
String StringData = "" + data;
try {
JSONArray rootArray = new JSONArray(StringData);
int len = rootArray.length();
for (int i = 0; i < len; ++i) {
JSONObject json = rootArray.optJSONObject(i);
String Job_Title = json.optString("Req_Title");
String Designation = json.optString("Req_Designation_Role");
String Job_Type = json.optString("Req_Job_Type");
String Salary = json.optString("Req_From_Sal");
if(Job_Title == null || Job_Title .trim().equals("null") ||Job_Title .trim().length<=0){
b1.setText("Job title not set.");
}else{
b1.setText("" +Job_Title);
}
if(Designation == null || Designation.trim().equals("null") ||Designation.trim().length() <= 0){
b3.setText("Job Designation not set.");
}else{
b3.setText("" +Designation);
}
if(Job_Type == null || Job_Type.trim().equals("null") || Job_Type.trim().length() <= 0){
b13.setText("Job Type not set.");
}else{
b13.setText("" +Job_Type);
}
if(Salary == null || Salary.trim().equals("null") || Salary.trim().length() <= 0){
b14.setText("Not yet Mentioned");
}else{
b14.setText(""+Salary);
}
}
}
}
});

Parse simple JSON Array without key

I need help with parsing simple JSONArray like this:
{
"text":[
"Morate popuniti polje tekst."
]
}
I have tried with this but I failed:
if (response_str != null) {
try {
JSONObject jsonObj = new JSONObject(response_str);
JSONArray arrayJson = jsonObj.getJSONArray("text");
for (int i = 0; i < arrayJson.length(); i++) {
JSONObject obj = arrayJson.optJSONObject(i);
error = obj.getString("text");
}
}
Your JSONArray is an array of Strings. You can iterate this way
JSONObject jsonObj = new JSONObject(response_str);
JSONArray arrayJson = jsonObj.getJSONArray("text");
for (int i = 0; i < arrayJson.length(); i++) {
String error = arrayJson.getString(i);
// Do something with each error here
}
You have a JSONArray text. There is no array of JSONObject.
{ // Json object node
"text":[ // json array text
"Morate popuniti polje tekst." // value
]
}
Just use
for (int i = 0; i < arrayJson.length(); i++) {
String value = arrayJson.get(i);
}
In fact there is no need for a loop as you have only 1 element in json array
You can just use
String value = (String) arrayJson.get(0); // index 0 . need to cast it to string
Or
String value = arrayJson.getString(0); // index 0
http://developer.android.com/reference/org/json/JSONArray.html
public Object get (int index)
Added in API level 1
Returns the value at index.
Throws
JSONException if this array has no value at index, or if that value is the null reference. This method returns normally if the value is JSONObject#NULL.
public boolean getBoolean (int index)
getString
public String getString (int index)
Added in API level 1
Returns the value at index if it exists, coercing it if necessary.
Throws
JSONException if no such value exists.
Try this:
JSONObject jsonObject = new JSONObject(response_str);
JSONArray arrayJson = jsonObject.getJSONArray("text");
String theString = arrayJson.getString(0);

Convert JSON key value pairs into JSON Array 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());

How do I use JSONObject in Android

I have the following Android java code:
String json = "{\"Name_1\":1,\"Name_2\":0,\"Name_3\":0}";
JSONObject object = new JSONObject(json);
String[] propertyNames = JSONObject.getNames(object);
values = new String[propertyNames.length];
for (int i = 0; i < propertyNames.length; i++) {
values[i] = String.valueOf(object.get(propertyNames[i]));
}
but I am getting the following error: The method getNames(JSONObject) is undefined for the type JSONObject.
What can I do to get the propertyNames?
Why not look at the JavaDoc? It tells you about the keys() method.
for (Iterator<String> it = object.keys(); it.hasNext(); ) {
String key = it.next();
// ...
}
Edit: get an array of keys:
List<String> keyList = new ArrayList<String>();
for (Iterator<String> it = object.keys(); it.hasNext(); ) {
String key = it.next();
keyList.add(key);
}
String[] keyArray = keyList.toArray(new String[keyList.size()]);

Categories

Resources