Open and edit value in JsonObject - android

I have local Json file in asset folder.
I use this code to open file
try {
is = getAssets().open("data.json");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
jsonString = is.toString();
jsonString = new String(buffer,"UTF-8");
myJson = new JSONObject(jsonString);
jsonArrayData = myJson.getJSONArray("diTich");
int leng = jsonArrayData.length();
for(int i = 0 ; i < leng ; i++) {
mTitle = jsonArrayData.getJSONObject(i).getString("title");
mDescription = jsonArrayData.getJSONObject(i).getString("description");
mAddress = jsonArrayData.getJSONObject(i).getString("address");
mStatus = jsonArrayData.getJSONObject(i).getString("status");
}
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
My's Json file
{
"ABCD": [
{
"title": "abcd",
"description": "abc",
"address": "bnc",
"image": "abcg",
"status": false
}
]
}
I retrieved value in JsonObject. Now I wanna edit value in this
For example, change value of key "status" from false to true.
How can I do this ? I don't know write replace it !
Thanks you guys !

You use the JSONObject.put() methods of the JSONObject class. So, in your example you could do this:
jsonArrayData.getJSONObject(i).put("status", true);
That will clobber the value that is currently there.

Related

Android : How to access a JSONObject

I'm new to Android and I have tried so many options to access the JSONObject which returns from an API call but I couldn't succeed as any of the solutions i looked for didn't work for me.
What i want is to access the JSONObject and keep the Id & Name in a Array. And then populate the Names in a AutoCompleteTextView. How do i properly access the JSONObject. Please help me with this. I'm stuck on this for more than a day.
Following is my Code handling the JSONObject.
#Override
public void processFinish(JSONObject output) {
Toast.makeText(MainActivity.this,"ProcessFinish",Toast.LENGTH_SHORT).show();
allStations = output;
if(output != null){
Toast.makeText(MainActivity.this,output.toString(),Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(MainActivity.this," Connection Failed!",Toast.LENGTH_SHORT).show();
}
}
Following is a sample output of my JSONObject
{
"SUCCESS": true,
"MESSAGE": "Found 398 Results!",
"NOFRESULTS": 3,
"RESULTS": {
"stationList": [
{
"stationCode": "ABN",
"stationID": 3,
"stationName": "ABLA"
},
{
"stationCode": "ADLA",
"stationID": 410,
"stationName": "ADLA"
},
{
"stationCode": "ANM",
"stationID": 11,
"stationName": "AHAMA"
}]
},
"STATUSCODE": "2000"
}
try this
try {
JSONObject obj= output.getJSONObject("RESULTS");
JSONArray dataArray= obj.getJSONArray(“stationList“);
for(int i=0;i<dataArray.length();i++)
{
JSONObject object1=dataArray.getJSONObject(i);
Strind id = object1.getString("stationID");
}
} catch (JSONException e) {
e.printStackTrace();
}
In This code output is your JSONObject result
try this
try {
JSONObject jsonObject = new JSONObject("response");
boolean status= jsonObject.getBoolean("SUCCESS");
String MESSAGE= jsonObject.getString("MESSAGE");
String NOFRESULTS= jsonObject.getString("NOFRESULTS");
String STATUSCODE= jsonObject.getString("STATUSCODE");
JSONObject obj=jsonObject.getJSONObject("RESULTS");
JSONArray jsonarray = obj.optJSONArray("stationList");
for (int i = 0; i < jsonarray.length(); i++){
JSONObject json_data = jsonarray.getJSONObject(i);
Log.e("stationCode",json_data.getString("stationCode"));
Log.e("stationID",json_data.getString("stationID"));
Log.e("stationName",json_data.getString("stationName"));
}
} catch (JSONException e) {
e.printStackTrace();
}
Have you tried using a JSON Array? For example you could use this method for storage:
JSONObject wgroup = new JSONObject(); //FINAL json object
try { //put initial data
wgroup.put("id", "2");
wgroup.put("user", "someone");
wgroup.put("stime", "2017-02-06 16:30:13");
wgroup.put("etime", "2017-02-06 19:30:13");
wgroup.put("real_dur", 3600);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
JSONArray jsonArray1 = new JSONArray(); //Create an array to store ALL Variables
for (int y=0; y< your_array.length ; y++ ){ //loop through your information array
JSONObject output = new JSONObject(); //CREATE a json object to put 1 workout
try {
wgroup.put("id", "2");
wgroup.put("name", "sam");
wgroup.put("age", "3");
wgroup.put("gender", "male");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
JSONArray jsonArray2 = new JSONArray(); //CREATE a json array to put 1 array
jsonArray1.put(output); //insert this OBJECT into the ARRAY
}
wgroup.put(jsonArray1);//insert the workouts ARRAY into the original object

Content is not allowed in prolog - parsing json

I'm attempting to use a json file to store user data for a dummy Android Studio project, and while trying to test the LoginActivity which reads in the file, I'm getting an error
Error:Execution failed for task ':app:mergeDebugResources'.
/Users/james/projects/cwm/app/src/debug/res/values/users.json:1:1: Error: Content is not allowed in prolog.
{
"users": [
{
"name": "James",
"email": "j#gmail.com",
"address": "addr1",
"password": "password",
"usertype": "USER"
},
{
"name": "Kayla",
"email": "k#gmail.com",
"address": "addr1",
"password": "password",
"usertype": "MANAGER"
}
]
}
And here is the code in the LoginActivity that I believe is causing the error:
private String loadJSONFromAsset() {
String json = null;
try {
InputStream is = this.getAssets().open("users.json");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
return json;
}
private void parseJ() {
try {
JSONObject jsonObject = new JSONObject(loadJSONFromAsset());
if(jsonObject != null) {
JSONArray jsonArray = jsonObject.getJSONArray("users");
if(jsonArray != null) {
for(int i = 0; i < jsonArray.length(); i++) {
JSONObject jo = jsonArray.getJSONObject(i);
if(jo != null) {
String name = (String) jo.get("name");
String email = (String) jo.get("email");
String address = (String) jo.get("address");
String password = (String) jo.get("password");
String userType = (String) jo.get("usertype");
User u = new User(name, email, address, password);
u.setUserType(userType);
userList.put(email, u);
a.setMessage(u.toString());
a.show();
}
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
I've searched stackoverflow and Google for a solution but most answers pertain to XML or JSON unmarshalling, which I don't believe is relevant to what I'm doing but I could be wrong. Thanks in advance!
/Users/james/projects/cwm/app/src/debug/res/values/users.json:1:1: Error: Content is not allowed in prolog.
Please move your users.json from res folder to assets folder and try again.
Because, getAssets() method refers to assets folder.
It's possible that a byte order mark prevents deserialization. Check that your editor doesn't add one.

How to parse this json string? [duplicate]

This question already has answers here:
Sending and Parsing JSON Objects in Android [closed]
(11 answers)
Closed 8 years ago.
i want to parse this json.i have difficulty when i try to parse the following json.suggest me proper way of parsing following json.i edit my code ,noe this is the correct code that i want to parse.
{
"tag":{
"tag1":1,
"tag2": "colour",
"tag3":"value",
"tag4":"value",
"tag5":1,
"tag6":1,
"tag7":true,
"tag8": [
{
"t1":"Red",
"t2":"int",
"t3":1,
"t4":true
},
{
"t1":"Green",
"t2":"int",
"t3":2,
"t4":true
},
{
"t1":"Blue",
"t2":"int",
"t3":3,
"t4":true
}
],
"tag9":null,
"tag10":1
},
"tag":{
"tag1":2,
"tag2": "value",
"tag3":"value",
"tag4":"value",
"tag5":1,
"tag6":1,
"tag7":true,
"tag8": [
{
"t1":"value",
"t2":"value",
"t3":true,
"t4":true,
},
{
"t1":"value",
"t2":"value",
"t3":false,
"t4":true,
}
],
"tag9":1,
"tag10":3
},
"tag":{
"tag1":5,
"tag2": "value",
"tag3":"value",
"tag4":"value",
"tag5":1,
"tag6":1,
"tag7":false,
"tag8": null,
"tag9":null,
"tag10":null
}
}
i had used this code
try {
JSONObject json= (JSONObject) new JSONTokener(loadJSONFromAsset()).nextValue();
JSONObject json2 = json.getJSONObject("tag");
for (int i = 0; i < json.length(); i++) {
int tag1 = (Integer) json2.get("tag1");
String tag2 = (String) json2.get("tag2");
String tag3 = (String) json2.get("tag3");
String tag4 = (String) json2.get("tag4");
int tag5 = (Integer) json2.get("tag5");
int tag6 = (Integer) json2.get("tag6");
boolean tag7 = json2.getBoolean("tag7");
if (!json2.isNull("tag8")) {
JSONArray jArray = json2.getJSONArray("tag8");
JSONObject json_data = null;
for (int i1 = 0; i1 < jArray.length(); i1++) {
json_data = jArray.getJSONObject(i1);
String Label = json_data.getString("t1");
String ValueType = json_data.getString("t2");
int Value = json_data.getInt("t3");
boolean isNextEnabled = json_data.getBoolean("t4");
}
}
int previous = 0;
if (!json2.isNull("tag9")) {
previous= (Integer) json2.get("tag9");
}
int next = 0;
if (!json2.isNull("tag10")) {
next = (Integer) json2.get("tag10");
}
}
} catch (JSONException e) {
e.printStackTrace();
}
public String loadJSONFromAsset() {
String json = null;
try {
InputStream is = getAssets().open("myjson");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
return json;
}
}
i get only last record ,how do i get all data .any help will be appreciated thanks...
You can try to parse your string # http://json.parser.online.fr/ it works nice for me.
From static review of the JSON string it seems you have "tag" element 3 times in your input and due to that parser might get confused. Try to remove duplicate entries and then try.
The JSONOject has a constructor that accepts a string of JSON data. You can use the constructor to parse the JSON string. If the string is valid JSON data, the constructor will return a JSONObject. If the string is NOT valid JSON, the constructor will throw an error. It's good practice to wrap the constructor inside of a try/catch block.
String json = "{name:\"value\"}";
JSONObject item = null;
try{
item = new JSONObject(json);
}catch(Exception exc){
Log.d(TAG, exc.toString());
}
if(item != null){
Log.d(TAG, String.format("name:%s", item.getString("name")));
}

Extract and Save Json to Arraylist Android

How can i extract the json below and save it in an arraylist.
{
"trains": {
"train": [
{
"#id": 1000000103,
"#version": 1,
"#status": "active",
"#name": "dffffff",
"#description": "ffffff half of the nineteenth century.",
"#city": "fff",
"#phone": "+230 595-1454",
"#email": "ffffr#mffc.mu",
"#website": "www4u",
"#latitude": -5.2882,
"#longitude": 3.499,
"#defaultLocale": "",
"#holes": 48,
"#par": 72,
"#slope": 0,
"#distance": 5.005273,
"circuits": {
"circuit": []
},
"localizations": {
"localization": []
}
},
{
"#id": 1000000105,
"#version": 1,
"#status": "active",
"#name": " xClub",
"#description": "",
"#city": " xlet",
"#phone": "+44465\t",
"#email": "",
"#website": "wweffl.com",
"#latitude": -2.040318,
"#longitude": 54548,
"#defaultLocale": "",
"#holes": 18,
"#par": 32,
"#slope": 0,
"#distance": 2441673,
"circuits": {
"circuit": []
},
"localizations": {
"localization": []
}
}
]
}
}
my working
try {
jobj_trouve_train = new JSONObject(reponse_trouve_train);
String jsonobj = jobj_trouve_golf.getString("trains");
//String jsonobj1 = jobj_trouve_golf.getString("train");
//jobj_trouve_train = new JSONObject(reponse_trouve_train);
//jsonArray = jobj_trouve_golf.getJSONArray("trains");
//jsonArray= new JSONArray(jsonobj);
//System.out.println("jsonArray "+jsonArray);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Try this..
try {
jobj_trouve_train = new JSONObject(reponse_trouve_train);
JSONObject jsonobj = jobj_trouve_train.getJSONObject("trains");
JSONArray jsonobj1 = jsonobj.getJSONArray("train");
for(int i = 0;i< jsonobj1.length();i++){
JSONObject jsonj = jsonobj1.getJSONObject(i);
System.out.println("#id "+jsonj.getString("#id"));
// Same for remaining all
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
You can use the Gson library developed by Google to parse Json into objects.
The reference is here:
https://code.google.com/p/google-gson/
And, a sample example is here:
JSON Parsing with GSON
JSONObject trains = jobj_trouve_train.getJSONObject("trains");
JSONArray trainArray = trains.getJSONArray("train");
JSONObject train1 = trainArray.getJSONObject(0);
...
if i didn't get confuse maybe this one will be right
JSONArray jasonArray = new JSONArray(result.getProperty("trains").toString());
for (int i = 0; i < jasonArray.length(); i++) {
JSONObject jsonObj = jasonArray.optJSONObject(i);
trainObject = new JSONObject(jsonObj.optString("train").toString());
int id = trainObject.optInt("id");
and so on..
}
public Object void toObject(String jsonMsg) throws JSONException {
JSONObject trains= (JSONObject) new JSONTokener(jsonMsg).nextValue();
if(trains.has("trains")){
JSONArray train = (JSONArray) new JSONTokener(object.getString("train")).nextValue();
for (int t = 0; t < jsonArray.length(); t++) {
String temp = jsonArray.getJSONObject(t).toString();
JSONObject object = (JSONObject) new JSONTokener(temp).nextValue();
if(object.has("#id"))
object.getString("#id");
// now similar procedure of reading
// read values and save it in an "object"
}
return savedObject;
}
-- tested, i have tried to modify code to match your JSON data. complete the rest.

JSON Parsing in android - from resource folder

I've a kept one text file in res/raw folder in eclipse. I am showing here the content of that file:
{
"Categories": {
"Category": [
{
"cat_id": "3",
"cat_name": "test"
},
{
"cat_id": "4",
"cat_name": "test1"
},
{
"cat_id": "5",
"cat_name": "test2"
},
{
"cat_id": "6",
"cat_name": "test3"
}
]
}
}
I want to parse this JSON array. How can I do this?
Can anybody please help me??
Thanks in advance.
//Get Data From Text Resource File Contains Json Data.
InputStream inputStream = getResources().openRawResource(R.raw.json);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
int ctr;
try {
ctr = inputStream.read();
while (ctr != -1) {
byteArrayOutputStream.write(ctr);
ctr = inputStream.read();
}
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
Log.v("Text Data", byteArrayOutputStream.toString());
try {
// Parse the data into jsonobject to get original data in form of json.
JSONObject jObject = new JSONObject(
byteArrayOutputStream.toString());
JSONObject jObjectResult = jObject.getJSONObject("Categories");
JSONArray jArray = jObjectResult.getJSONArray("Category");
String cat_Id = "";
String cat_name = "";
ArrayList<String[]> data = new ArrayList<String[]>();
for (int i = 0; i < jArray.length(); i++) {
cat_Id = jArray.getJSONObject(i).getString("cat_id");
cat_name = jArray.getJSONObject(i).getString("cat_name");
Log.v("Cat ID", cat_Id);
Log.v("Cat Name", cat_name);
data.add(new String[] { cat_Id, cat_name });
}
} catch (Exception e) {
e.printStackTrace();
}
This is your code:
String fileContent;
JSONObject jobj = new JSONObject(fileContent);
JSONObject categories = jobj.getJSONObject("Categories");
JSONArray listCategory = categories.getJSONArray("Category");
for( int i = 0; i < listCategory.length(); i++ ) {
JSONObject entry = listCategory.getJSONObject(i);
//DO STUFF
}
Android framework has a helper JsonReader in android.util package
Works like a charm, presented great example. In first block small error with absent square bracket '}':
public List readJsonStream(InputStream in) throws IOException {
JsonReader reader = new JsonReader(new InputStreamReader(in, "UTF-8"));
try {
return readMessagesArray(reader);
} finally {
reader.close();
}
}
Also exists great library from google-devs GSON, which gives you possibility to map json structure straight to Java model: take a look here
Read it into a String
Create a JSONArray with the retrieved String
Use get() methods to retrieve its data

Categories

Resources