JSONObject is not updated correctly - java

I am, updating the value in a JSONObject that is inside a JSONArray, when changing the value is updating in all the JSONArray. Does anybody know why?
public static void uploadMediaWithThumbnail( final LeagueActivity.UploadingCallback call,
final long leagueId,
final JSONArray information, final JsonHttpResponseHandler handler) {
final AtomicInteger receivedCount = new AtomicInteger();
receivedCount.set(0);
call.progressCall(10);
getMediaUploadUrl(leagueId, information, new JsonHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
try {
call.progressCall(20);
final JSONArray allData = response.getJSONArray("upload_data");
AsyncHttpClient[] clients = new AsyncHttpClient[allData.length()*2];
JSONArray jarr = information;
for (int i = 0; i < allData.length(); i++ ) {
final String uploadUrl = allData.getJSONObject(i).getString("content_url");
final String previewUrl = allData.getJSONObject(i).getString("preview_url");
jarr.getJSONObject(i).put("content", uploadUrl);
jarr.getJSONObject(i).put("preview", previewUrl);
}
final JSONArray newInfo = shallowCopy(jarr);
Log.d("Log1", newInfo.getJSONObject(1).getString("content"));
Log.d("Log2", newInfo.getJSONObject(0).getString("content"));
When logging Log1 and Log2 they contain the same link
information is a data like this [{"type":"video","format":"mp4","preview_format":"jpg"}, {"type":"video","format":"mp4","preview_format":"jpg"}]
AllData is information received from an REST HTTP call and has the same length as information

Thanks for the update.
You want to add the items for information into a JSONObject, and then add that object to your JSONArray.
JSONArray jarr = information;
for (int i = 0; i < allData.length(); i++ ) {
final String uploadUrl = allData.getJSONObject(i).getString("content_url");
final String previewUrl = allData.getJSONObject(i).getString("preview_url");
JSONObject object = new JSONObject();
object.put("content", uploadUrl);
object.put("preview", previewUrl);
jarr.put(i, object);
}
After the for loop, you can then get the values from the keys.
Or, if jarr already has objects...
JSONArray jarr = information;
for (int i = 0; i < allData.length(); i++ ) {
final String uploadUrl = allData.getJSONObject(i).getString("content_url");
final String previewUrl = allData.getJSONObject(i).getString("preview_url");
JSONObject object = new jarr.getJSONObject(i);
object.put("content", uploadUrl);
object.put("preview", previewUrl);
jarr.put(i, object);
}
this isnt tested, but should work. haha

Try like this,
JSONArray jsonArray;
try {
//here replace with your data object
jsonArray = new JSONArray(" [{\"type\":\"video\",\"format\":\"mp4\",\"preview_format\":\"jpg\"}, {\"type\":\"video\",\"format\":\"mp4\",\"preview_format\":\"jpg\"}]");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
jsonObject.put("content", "test value " + i);
}
Log.d("Print test", jsonArray.getJSONObject(0).toString());
Log.d("Print test", jsonArray.getJSONObject(1).toString());
} catch (
JSONException e) {
e.printStackTrace();
}

Related

I am trying to write my Object into a Json File after converting it in JsonObject but it is not getting written

Here is my data (value in myRecords) :
[Record{Purpose='Medical ', ID='9215524400 ', UpdateTime='2020-10-14', Checkin='2020-10-14'},...]
Here is my code :
private FileWriter file;
JSONArray jsonArr = new JSONArray(myRecords);
for (int i = 0; i < jsonArr.length(); i++) {
JSONObject jsonObj = jsonArr.getJSONObject(i);
file = new FileWriter("NewFile.json");
file.write(String.valueOf(jsonObj));
}
I am not getting any errors but nothing is getting written into the file.
I think this statement is not working as expected:
JSONArray jsonArr = new JSONArray(myRecords);
You would need to define object to JSON conversion yourself. You can define a toJSON() method in your Record class:
private static class Record {
private String purpose, id, updateTime, checkIn;
public Record(String purpose, String id, String updateTime, String checkIn) {
this.purpose = purpose;
this.id = id;
this.updateTime = updateTime;
this.checkIn = checkIn;
}
public JSONObject toJSON() {
JSONObject jo = new JSONObject();
jo.put("purpose", this.purpose);
jo.put("id", this.id);
jo.put("updateTime", this.id);
jo.put("checkIn", this.id);
return jo;
}
}
Then you can simply stream over your Record array to call toJSON() for each object:
Record[] myRecords = {
new Record("Medical", "1", "2020-10-14", "2020-10-14"),
new Record("Pharma", "2", "2020-10-14", "2020-10-14"),
new Record("Security", "3", "2020-10-14", "2020-10-14"),
};
JSONArray jsonArr = new JSONArray();
Arrays.stream(myRecords).forEach(r -> jsonArr.put(r.toJSON()));
You can then proceed to iterate over your JSONArray and then write each contents to the file, if you don't want file to be overwritten; you would need to set append flag to true:
for (int i = 0; i < jsonArr.length(); i++) {
JSONObject jsonObj = jsonArr.getJSONObject(i);
try (FileWriter file = new FileWriter("NewFile.json", true)) {
file.write(jsonObj.toString());
}
}
You can also write the JSONArray directly to file like this:
JSONArray jsonArr = new JSONArray();
Arrays.stream(myRecords).forEach(r -> jsonArr.put(r.toJSON()));
try (FileWriter fileWriter = new FileWriter("NewFileCompleteArr.json", true)) {
fileWriter.write(jsonArr.toString());
}
you need to close the FileWriter
file.close()

getJSONArray() in GraphResponse Cannot be applied to java.lang.String - Facebook

i have develop a android application integrate with facebook login now i want to make facebook app invite function(invitable_friends api) but in my code i got red underline errors.
private void loadFriendsFromFacebook(final String str) {
final AccessToken accessToken = AccessToken.getCurrentAccessToken();
new GraphRequest(AccessToken.getCurrentAccessToken(), str, null, HttpMethod.GET,
new GraphRequest.Callback() {
List<String> s = new ArrayList();
List<String> F = new ArrayList();
List<String> G = new ArrayList();
String t = "";
String u = "";
int w = 0;
boolean x = false;
String[] y = new String[2];
String E = "";
OnInviteListener onInviteListener = null;
public void onCompleted(GraphResponse response) {
SharedPreferences.Editor edit = getSharedPreferences("friendsData", 0).edit();
try {
int i;
JSONArray jSONArray = response.getJSONArray("data");
for (i = 0; i < jSONArray.length(); i++) {
this.s.add(jSONArray.getJSONObject(i).getString(Page.Properties.ID));
}
for (i = 0; i < jSONArray.length(); i++) {
this.G.add(jSONArray.getJSONObject(i).getJSONObject(Page.Properties.PICTURE).getJSONObject("data").getString("url"));
edit.putString("friendPhoto", jSONArray.getJSONObject(i).getJSONObject(Page.Properties.PICTURE).getJSONObject("data").getString("url"));
this.F.add(jSONArray.getJSONObject(i).getString(Page.Properties.NAME));
edit.putString("friendName", jSONArray.getJSONObject(i).getString(Page.Properties.NAME));
}
edit.commit();
for (i = 0; i < this.s.size(); i++) {
this.u += ((String) this.s.get(i)) + ",";
}
JSONObject jSONObject2 = response.getJSONObject("paging");
if (jSONObject2.toString().contains("next")) {
this.t = jSONObject2.getString("next").toString();
} else if (this.s.size() < 1) {
this.x = true;
}
} catch (Exception e) {
System.out.println("Exception=" + e);
e.printStackTrace();
}
}
}).executeAsync();
}
where the response.getJSONArray("data");
data is underline red which is click rover shows getJSONArray() in graphrespone cannot be applied to java.lang.sting..
and same error in the response.getJSONObject("paging");
Can anyone please tell me what is wrong in the code?
it will be appreciated..
From here (https://developers.facebook.com/docs/reference/android/current/class/GraphResponse/) I can see that getJSONObject() and getJSONArray() do not have parameters at all. You should retrieve the object respective the array from the GraphResponse using this methods and once you have a JsonObject or JsonArray you can access specific fields.
response.getJSONArray() will give you an object of type JSONArray and response.getJSONObject() will give you an object of type JSONObject. Using this objects you can access the fields using jsonObject.getString("user_id") or similar (see docs.oracle.com/javaee/7/api/javax/json/JsonObject.html)

Trying to parse JSON in Android

How would you suggest me to parse this JSON:
{"17": {"user_name": "test1"}, "18": {"user_name": "test5"}, "19": {"user_name": "test9"}}
I need to get "username",but i cant find the way to do it. Maybe i should change JSON to something like that:
[{"user_name": "test1"},{"user_name": "test5"},{"user_name": "test9"}]
This way i tried to get "user_name"s:
try {
List<String> allNames = new ArrayList<String>();
String str = "[{"user_name": "test1"},{"user_name": "test5"},{"user_name": "test9"}]";
JSONObject json = new JSONObject(str);
for ( int i = 0; i < json.length() ; i++)
{
JSONObject actor = json.getJSONObject(i);
String user_name = actor.getString("user_name");
allNames.add(user_name);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
But then i get Problem with that line:
JSONObject actor = json.getJSONObject(i);
Android studio tells me that JSONObject cannot be applied to int(i). I have no idea why it doesn't work.
Can somebody please give me some hint, tutorial or an example?
Much appreciated !
The method JSONObject.getJSONObject requires a String argument (the name or key of the object), not an int. In your case, the keys are "17", "18" and "19". To get all keys, use the JSONObject.keys() method:
JSONObject json = new JSONObject(str);
Iterator<String> keyIterator = json.keys();
while (keyIterator.hasNext()) {
JSONObject actor = json.getJSONObject(keyIterator.next());
String user_name = actor.getString("user_name");
allNames.add(user_name);
}
Android studio tells me that JSONObject cannot be applied to int(i)
Because JSONObject.getJSONObject method takes key name as String instead of int. and keys in posted json is 17,18,... to access inner JSONObject.
To get all user_name from JSONObject,need to get all keys:
Iterator<String> iter = json.keys();
while (iter.hasNext()) {
String key = iter.next();
JSONObject actor = json.getJSONObject(key);
String user_name = actor.getString("user_name");
allNames.add(user_name);
}
Change your code like this
try {
List<String> allNames = new ArrayList<String>();
String str = "[{"user_name": "test1"},{"user_name": "test5"},{"user_name": "test9"}]";
JSONOArray jsonArray = new JSONOArray(str);
for ( int i = 0; i < jsonArray .length() ; i++)
{
JSONObject actor = jsonArray.getJSONObject(i);
String user_name = actor.getString("user_name");
allNames.add(user_name);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if you use the Gson library it's very easy.
String json = "{\"17\": {\"user_name\": \"test1\"}, \"18\": {\"user_name\": \"test5\"}, \"19\": {\"user_name\": \"test9\"}}";
Gson gson = new GsonBuilder().create();
Map<String,User> users = gson.fromJson(json, new TypeToken<Map<String,User> >(){}.getType());
for(String key : users.keySet()) {
Log.d("DEBUG",key+" -> "+users.get(key).getUser_name());
}
The User class is a simple POJO like:
public class User {
private String user_name;
public String getUser_name() {
return user_name;
}
public void setUser_name(String user_name) {
this.user_name = user_name;
}
}
str = {"17": {"user_name": "test1"}, "18": {"user_name": "test5"}, "19": {"user_name": "test9"}}
JSONObject ob1 = new JSONObject(str)
JSONObject ob2 = ob1.getJSONObject("17");
String userName = ob2.getString("user_name");
str = [{"user_name": "test1"},{"user_name": "test5"},{"user_name": "test9"}]
List<String> allNames = new ArrayList<String>();
JSONArray jsonArray = new JSONArray("str");
for(i=0; i < jsonArray.length(); i++){
JSONObject ob = jsonArray.getJSONObject(i);
allNames.add(ob.getString("user_name")
}
you are trying to parse JSONArray into JSONObject at
JSONObject json = new JSONObject(str);
use the below code.....
try {
List<String> allNames = new ArrayList<String>();
String str = "[{"user_name": "test1"},{"user_name": "test5"},{"user_name": "test9"}]";
JSONArray json = new JSONArray(str);
for ( int i = 0; i < json.length() ; i++)
{
JSONObject actor = json.getJSONObject(i);
String user_name = actor.getString("user_name");
allNames.add(user_name);
}
} catch (JSONException e) {
// TODO Auto-generated catch block`enter code here`
e.printStackTrace();
}

JsonArray to List in Java

I have a problem with parsing JsonArray response.
I take JsonObject from JsonArray, parse it and set in entity message and then that message add to ArrayList.
Problem is that in ArrayList that I want to return I always have only one message. This must be some fundamental error but I cant find it.
public ArrayList<Message> getSearchInfo(String response) {
ArrayList<Message> searchResult = new ArrayList<Message>();
int jsonMessageId = -1;
String jsonDate = "";
String jsonText = "";
String jsonAutor = "";
String jsonSource = "";
int jsonThemeID = -1;
int jsonSourceID = -1;
try {
JSONArray jArray = new JSONArray(response);
if (jArray != null) {
for (int i = 0; i < jArray.length(); i++) {
try {
JSONObject oneObject = jArray.getJSONObject(i);
Message m = new Message();
// Pulling items from the array
jsonMessageId = oneObject.getInt("MessageId");
jsonDate = oneObject.getString("CreatedDate");
jsonText = oneObject.getString("TextMessage");
jsonAutor = oneObject.getString("Autor");
jsonSource = oneObject.getString("Source");
jsonThemeID = oneObject.getInt("ThemeId");
jsonSourceID = oneObject.getInt("SourceId");
m.setMessageId(jsonMessageId);
m.setMessageText(jsonText);
m.setDate(jsonDate);
m.setAutor(jsonAutor);
m.setSource(jsonSource);
m.setThemeId(jsonThemeID);
m.setSourceId(jsonSourceID);
searchResult.add(m);
} catch (JSONException e) {
Log.d("URL EXC", "Exception 2");
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return searchResult;
}
p.s. I use web-api as service and via android I take resources from service.
Any idea where is my mistake here?
You redefine your list every time in the loop.
Change your code from
JSONArray jArray = new JSONArray(response);
if (jArray != null) {
for (int i = 0; i < jArray.length(); i++) {
try {
searchResult = new ArrayList<Message>();
To
JSONArray jArray = new JSONArray(response);
if (jArray != null) {
searchResult = new ArrayList<Message>();
for (int i = 0; i < jArray.length(); i++) {
try {

Get JSON Array into strings.

I have a webservice which returns a JSON array in this format:
[{"imageid":"3","userid":"1","imagepath":"SLDFJNDSKJFN","filterid":"1","dateadded":"2014-05-06 21:20:18.920257","public":"t"},
{"imageid":"4","userid":"1","imagepath":"dsfkjsdkfjnkjdfsn","filterid":"1","dateadded":"2014-05-06 21:43:37.642748","public":"t"}]
I need to get all the attributes seperately? How would I do this?
I know how to do it with JSONObject if there is just 1 thing being returned, but how does it work when multiple items are returned?
Thanks
try {
JSONArray jArray = new JSONArray(jsonString);
String s = new String();
for (int i = 0; i < jArray.length(); i++) {
s = jArray.getJSONObject(i).getString("imageid").toString();
s = jArray.getJSONObject(i).getString("userid").toString();
}
} catch (JSONException je) {
}
Create an Object class with all variables, create a List for this Object, add all objects in your JSONArray to the list, use the one you need.
List<YourObject> objList = new ArrayList<YourObject>();
JSONArray a = new JSONArray(response);
int size = a.length();
for (int i=0 ; i<size ; i++){
JSONObject aa = a.getJSONObject(i);
String id = aa.getString("imageid");
String userid = aa.getString("userid");
String imagepath = aa.getString("imagepath");
String filterid = aa.getString("filterid");
String dateadded = aa.getString("dateadded");
String publicText = aa.getString("public");
YourObject obj = new YourObject(id,userid,imagepath,filterid,dateadded,publicText);
objList.add(obj);
}
So what you are having here is some JSON objects inside a JSON array.
What you want to do is this:
JSONArray array = ...;
for (int i = 0; i < array.length(); i++) {
JSONObject o = array.getJSONObject(i);
// Extract whatever you want from the JSON object.
}
I hope it helped.
You can use JSONArray to parse array of JSON response.
private void parseJsonArray(String response) {
try {
JSONArray array = new JSONArray(response);
for(int i=0;i<array.length();i++){
JSONObject jsonObject = array.getJSONObject(i);
String ImageId = jsonObject.getString("imageid");
Log.v("JSON Parser", "ImageId: "+ImageId);
}
} catch (Exception e) {
e.printStackTrace();
}
}

Categories

Resources