How to serially get JSONObject from a txt file - android

I kept some JSON data in a txt file inside assests folder. Then i am reading the txt file and kept the result in a string. Now i am trying to convert the string to JSONObject and get some data from each key. Below is the code.
========method for reading from a file:
private String readMyJsonFile()
{
BufferedReader reader = null;
try {
reader = new BufferedReader(
new InputStreamReader(getAssets().open("myFile.txt"), "UTF-8"));
mLine = reader.readLine();
} catch (IOException e) {
//log the exception
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
//log the exception
}
}
}
return mLine;
}
======= And inside onCreate():
String JsonStr = readMyJsonFile();
try {
JSONObject jsonObj = new JSONObject(JsonStr);
JSONObject questionMark = JsonObj.getJSONObject("structure_details");
Iterator keys = questionMark.keys();
while(keys.hasNext())
{
String currentDynamicKey = (String)keys.next();
JSONObject currentDynamicValue = questionMark.getJSONObject(currentDynamicKey);
}
}
catch (JSONException e) {e.printStackTrace(); }
================================================
and the JSON data is:
{"structure_details":{"x1":{"id":"54","name":"sh"},
"x2":{"id":"69","name":"dd"},
"x3":{"id":"80","name":"kk"}
}
}
==========================================================
I am getting result but the problem is that i am not getting the JSONObject serially in JSONObject jsonObj = new JSONObject(JsonStr); . The sequence is not the same as the JsonStr.
How to solve it?

Take the iterator keys in a ArrayList of string. Then loop through each arraylist object and get the JsonObjects. Following is the code that might help:
String JsonStr = readMyJsonFile(); //readMyJsonFile() is the same method you created
ArrayList<String> sortedKey = new ArrayList<String>();
try {
JSONObject jsonObj = new JSONObject(JsonStr);
JSONObject questionMark = jsonObj.getJSONObject("structure_details");
Iterator keys = questionMark.keys();
while(keys.hasNext()) {
String currentDynamicKey = (String)keys.next();
sortedKey.add(currentDynamicKey);
}
Collections.sort(sortedKey);
for(String str:sortedKey )
{ JSONObject currentDynamicValue = questionMark.getJSONObject(str);
}
}
catch (Exception e) {
e.printStackTrace();
}

It is not JSON:
"structure_details":{"x1":{"id":"54","name":"sh"},
"x2":{"id":"69","name":"dd"},
"x3":{"id":"80","name":"kk"}
}
It is JSON:
{"structure_details":{"x1":{"id":"54","name":"sh"},
"x2":{"id":"69","name":"dd"},
"x3":{"id":"80","name":"kk"}
}}
and it JSON:
{"x1":{"id":"54","name":"sh"},
"x2":{"id":"69","name":"dd"},
"x3":{"id":"80","name":"kk"}
}

Related

How to get JSONObject without JSONArray

I have such a JSON: https://paste.ubuntu.com/p/HkTK9xTzNx/
How do I get a "imdb_id" String (line 14). There is no array which contains that value,it's not in square branches,so I don't know how to get it.
Solution as per your need:
try {
imdbLink = response.getString("imdb_id");
} catch (JSONException e) {
e.printStackTrace();
}
A standard solution:
String json = "{\"imdb_id\":\"str12345\"}"; // your json response from network call/local file
JSONObject jsonObject;
try {
jsonObject = new JSONObject(json);
String id = jsonObject.getString("imdb_id");
} catch (Exception e) {
e.printStackTrace();
}

why is a JSON file not getting read by my app?

I am new to Stackoverflow and this is my first question.
I am developing an application where I am reading data from a json file from assets folder and storing the values in array list.
here is my code
try {
JSONObject object=new JSONObject(loadJSONFromAsset());
String objec=object.getString("root");
JSONObject object1=new JSONObject(objec);
JSONArray array=object1.getJSONArray("child");
for (int i=0;i<array.length();i++)
{
JSONObject jsonObject=array.getJSONObject(i);
list.add(String.valueOf(jsonObject));
}
} catch (JSONException e) {
e.printStackTrace();
}
// Inflate the layout for this fragment
return rootview;
}
public String loadJSONFromAsset() {
String json = null;
try {
InputStream is = getActivity().getAssets().open("data.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;
}
And this is my json data structure
"root" : {
"child" : [ "data1","data2","data3",.......]},
I want the data1,data2 values inside a list
Try this
try {
JSONObject object=new JSONObject(loadJSONFromAsset());
String objec=object.getString("root");
JSONObject object1=new JSONObject(objec);
JSONArray array=object1.getJSONArray("child");
for (int i=0;i<array.length();i++)
{
list.add(array.getString(i));
}
} catch (JSONException e) {
e.printStackTrace();
}
try {
JSONObject object=new JSONObject(loadJSONFromAsset());
String objec=object.getString("root");
JSONObject object1=new JSONObject(objec);
JSONArray array=object1.getJSONArray("child");
for (int i=0;i<array.length();i++)
{
JSONObject jsonObject=array.getJSONObject(i);
list.add(jsonObject.getString(i));
}
} catch (JSONException e) {
e.printStackTrace();
}

How to access volley response like this

How to access volley response {"data":"success"} like this.
i am already try this
JSONObject j = null;
try {
j = new JSONObject(response);
result = j.getJSONArray("data");
} catch (JSONException e) {
e.printStackTrace();
}
You're trying to access a JSONArray from a JSONObject while it's just a string. So just replace getJSONArray with getString and try this
String data = new JSONObject(response).getString("data");
Or in your code
try {
JSONObject j = new JSONObject(response);
result = j.getString("data");
}
catch (JSONException e) {
e.printStackTrace();
}
Access Like This
JSONObject j = null;
try {
j = new JSONObject(response);
result = j.getString("data");
} catch (JSONException e) {
e.printStackTrace();
}
You can check this, before retrieving check if that tag (i.e. "data" for your case) is exists on that json object.
JSONObject j = null;
try {
j = new JSONObject(response);
if(j.has("data") {
result = j.getString("data");
}
} catch (JSONException e) {
e.printStackTrace();
}
As the value of data is string and to get string value you have to use JSONObject.getString("data")
Use:
result = j.getString("data");
Instead of:
result = j.getJSONArray("data");

Write to file JSON into assets folder Android

I have a file (ex.json) from which I take the data
{
"Adres": "ул. Курчатова, 10",
"Comment": "В здании вокзала, на 1 и на 2 этаже",
"Dobavil": "Сергей",
"location": {
"latitude": 48.474721,
"longitude": 35.008587
},
"objectId": "sVjaCW0JV4"
}
doing so
public void update()
StringBuffer sb = new StringBuffer();
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(getAssets().open("ex.json")));
String temp;
while ((temp = br.readLine()) != null)
sb.append(temp);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
br.close(); // stop reading
} catch (IOException e) {
e.printStackTrace();
}
}
String myjsonstring = sb.toString();
try {
JSONObject jsonObjMain = new JSONObject(myjsonstring);
JSONArray jsonArray = jsonObjMain.getJSONArray("results");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObj = jsonArray.getJSONObject(i);
String adres = jsonObj.getString("Adres");
String comment = jsonObj.getString("Comment");
String dobavil = jsonObj.getString("Dobavil");
JSONObject c = jsonArray.getJSONObject(i);
JSONObject location = c.getJSONObject("location");
String lat = location.getString("latitude");
String lon = location.getString("longitude");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
I want to know whether you can append data to the file?
How do I write a string and an array of location?
It might be easier to do it with a text file?
I want to know whether you can append data to the file?
Assets are read-only at runtime. You are welcome to write your data to internal storage (e.g., getFilesDir()). When you go to read in the data, check to see if you have a modified copy in internal storage, and use it if it exists. Otherwise, fall back to loading the data from assets, as you are presently doing.
How do I write a string and an array of location?
Use JSONObject or JsonWriter. Or, encode the data in some other format (e.g., XML, CSV). Or, use a database.

How to Parse only some selected Json arrays and Json Objects from a Url to android device

I have a Json data and which contains multiple JSON arrays and JSON Objects so i want to parse some of them in an android activity ,...
Example of JSON array and Json objects at here
So i want to call some of them in the android device....
i know how to parse but i want only some of contents ,..
I have the data like
{
"process":"done"
"one":1
"List": {
"Something": [
{
"Name": "John",
"phone": "test"
}
]
"details":"ok"
"two":2
"SomethingElse": [
{
"Name": "Smith",
"phone": "test"
}
]
}
}
Like that i have a Restful service and it has lot of data ,.. so if want to call "list" or "SomethingElse" jsonObjecs/arrays.... its not calling its strucking at starting,..
You could consider parsing your data the SAX way, just go through your nodes, if it's what you need parse it, otherwise skip it and go on. Have a look here, JSONReader is the way to go.
Json Array for your above response will be like this
JSONObject JObject = new JSONObject(response);
String Process = JObject.getstring("process");
String one= JObject.getstring("one");
JSONObject Listobject= JObject.getjsonobject("List");
JsonArray something =Listobject.getjsonarray("Something");
for(int i = 0 ; i < something.length(); i++){
JsonObject somethingobject =something.getjsonobject(i);
String name=somethingobject.getstring("Name");
String phone=somethingobject.getstring("phone");
}
String details= JObject.getstring("details");
String two= JObject.getstring("two");
JsonArray SomethingElse=JObject.getjsonarray("SomethingElse");
for(int j = 0 ; j < SomethingElse.length(); j++){
JsonObject SomethingElseobject =SomethingElse.getjsonobject(j);
String name1=SomethingElseobject .getstring("Name");
String phone1=SomethingElseobject .getstring("phone");
}
Code for getting data from server
public void run() {
Log.i("run method", "calling run method");
try {
if (method == HttpMethodType.GET) {
response(executeHttpGet());
} else {
response(executeHttpPost());
}
} catch (ConnectTimeoutException ex) {
exception("Please retry after sometime...");
} catch (UnknownHostException e) {
exception("Server might be down...");
} catch (IOException e) {
exception("Please check your internet connectivity...");
} catch (Exception e) {
exception(e.getMessage());
}
Log.i(tag, "Http Call Finish");
}
private void response(String response) {
if (resListener != null) {
resListener.handleResponse(response);
}
}
private void exception(String exception) {
if (excepListener != null) {
excepListener.handleException(exception);
}
}
public String executeHttpGet() throws Exception {
Log.i("calling method", "calling execute");
Log.i("path in method", path);
BufferedReader in = null;
String page = null;
try {
HttpGet request = new HttpGet(path);
HttpResponse response = client.execute(request,localContext);
Log.i("======", response.toString());
in = new BufferedReader(new InputStreamReader(response.getEntity()
.getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
while ((line = in.readLine()) != null) {
Log.i("the response is ::", line);
sb.append(line);
}
in.close();
page = sb.toString();
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return page;
}

Categories

Resources