I have a json file stored in my assets folder (map_location.json) i need to display map markers parsed from the json file.Here's my json file:
{
"Dine": [
{
"id": 1,
"name": "Place Name",
"address": "Place Address",
"lat": -33.867,
"lng": 151.206
}
]
}
First you need to read JSON file from asset using bellow method:
public String loadJSONFile() {
String jsonStr = null;
try {
InputStream is = getAssets().open("map_location.json");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
jsonStr = new String(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
return jsonStr;
}
Then you read returned jSON string using this code:
JSONObject obj = new JSONObject(loadJSONFile());
JSONArray m_jArry = obj.getJSONArray("Dine");
ArrayList<Double> latList= new ArrayList<Double>();
ArrayList<Double> lngList= new ArrayList<Double>();
ArrayList<String> nameList= new ArrayList<String>();
ArrayList<String> addressList= new ArrayList<String>();
for (int i = 0; i < m_jArry.length(); i++)
{
JSONObject jo_inside = m_jArry.getJSONObject(i);
String name_value = jo_inside.getString("name");
String address_value = jo_inside.getString("address");
double lat_value = jo_inside.getDouble("lat");
double lng_value = jo_inside.getDouble("lng");
nameList.add(name_value);
addressList.add(address_value);
latList.add(lat_value);
lngList.add(lng_value);
}
Related
I'm creating an app to get posts from a web server, and i'm getting a jsonarray to object error I'm new to android development and tutorials i see the JsonArray is named before, so it'd be array of dogs, and then inside that would have breed and name and so on, mines not named.
the code i have is
public class GetData extends AsyncTask<String, String, String>{
#Override
protected String doInBackground(String... strings) {
String current = "";
try{
URL url;
HttpURLConnection urlConnection = null;
try{
url = new URL(JSONURL);
urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = urlConnection.getInputStream();
InputStreamReader isr = new InputStreamReader(in);
int data = isr.read();
while(data !=-1){
current += (char) data;
data = isr.read();
}
return current;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
finally {
if(urlConnection !=null){
urlConnection.disconnect();;
}
}
}catch (Exception e){
e.printStackTrace();
}
return current;
}
#Override
protected void onPostExecute(String s) {
try{
JSONObject jsonObject = new JSONObject(s);
JSONArray jsonArray = jsonObject.getJSONArray("");
for(int i = 0; i<jsonArray.length();i++){
JSONObject jsonObject1= jsonArray.getJSONObject(i);
namey = jsonObject1.getString("name");
post = jsonObject1.getString("post");
//hashmap
HashMap<String, String> posts = new HashMap<>();
posts.put("name", namey);
posts.put("post", post);
postList.add(posts);
}
} catch (JSONException e) {
e.printStackTrace();
}
//Displaying the results
ListAdapter adapter = new SimpleAdapter(
MainActivity.this,
postList,
R.layout.item,
new String[]{"name", "post"},
new int[]{R.id.textView, R.id.textView2});
lv.setAdapter(adapter);
}
}
the json code i'm trying to parse is
[
{
"0": "2",
"id": "2",
"1": "anon",
"name": "anon",
"2": "goodbye people of skivecore",
"post": "goodbye people of skivecore",
"3": "38.751053",
"lat": "38.751053",
"4": "-90.432915",
"lng": "-90.432915",
"5": "",
"ip": "",
"6": "6.204982836749738",
"distance": "6.204982836749738"
},
{
"0": "1",
"id": "1",
"1": "anon",
"name": "anon",
"2": "hello people of skivecore",
"post": "hello people of skivecore",
"3": "38.744453",
"lat": "38.744453",
"4": "-90.607986",
"lng": "-90.607986",
"5": "",
"ip": "",
"6": "9.280600590285143",
"distance": "9.280600590285143"
}
]
and stacktrace message
2021-04-28 23:45:02.156 20352-20352/com.skivecore.secrets W/System.err: org.json.JSONException: Value [{"0":"2","id":"2","1":"anon","name":"anon","2":"goodbye people of skivecore","post":"goodbye people of skivecore","3":"38.751053","lat":"38.751053","4":"-90.432915","lng":"-90.432915","5":"","ip":"","6":"6.204982836749738","distance":"6.204982836749738"},{"0":"1","id":"1","1":"anon","name":"anon","2":"hello people of skivecore","post":"hello people of skivecore","3":"38.744453","lat":"38.744453","4":"-90.607986","lng":"-90.607986","5":"","ip":"","6":"9.280600590285143","distance":"9.280600590285143"}] of type org.json.JSONArray cannot be converted to JSONObject
You should use like below
try {
JSONArray jsonArray = new JSONArray(s);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject1 = jsonArray.getJSONObject(i);
namey = jsonObject1.getString("name");
post = jsonObject1.getString("post");
//hashmap
HashMap<String, String> posts = new HashMap<>();
posts.put("name", namey);
posts.put("post", post);
postList.add(posts);
}
} catch (JSONException e) {
e.printStackTrace();
}
I think here is the issue JSONObject jsonObject = new JSONObject(s); as I can see your response is a JSONArray because it has [ and ] at the beginning and the end.
So, I think this would be more appropriate.
try{
JSONArray jsonArray = jsonObject.getJSONArray(s);
for(int i = 0; i<jsonArray.length();i++){
JSONObject jsonObject1= jsonArray.getJSONObject(i);
namey = jsonObject1.getString("name");
post = jsonObject1.getString("post");
//hashmap
HashMap<String, String> posts = new HashMap<>();
posts.put("name", namey);
posts.put("post", post);
postList.add(posts);
}
}
please usding gson library To use jasonArray And JsonObject Easley
1). https://github.com/google/gson
2). libraby import then use
https://www.jsonschema2pojo.org/
for your jsonArray to Model class
Then Use jsonArray
Use this instead....
try {
JSONArray jsonArray = new JSONArray(s);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject1 = jsonArray.getJSONObject(i);
namey = jsonObject1.getString("name");
post = jsonObject1.getString("post");
//put to hashmap
HashMap<String, String> posts = new HashMap<>();
posts.put("name", namey);
posts.put("post", post);
postList.add(posts);
}
} catch (JSONException e) {
e.printStackTrace();
I am trying to extract some data from a json array file, i followed the steps from
Reading a Json Array in android
a snippit of the json array:
[
{
"JobNo": 1,
"JobTime": 30,
"JobDate": "20170911",
"WorkerTime": 27,
"JobTimeError": -3
},
{
"JobNo": 2,
"JobTime": 22,
"JobDate": "20170911",
"WorkerTime": 21,
"JobTimeError": -1
},
What i want to be able to do is, extract the data and store them into their own arrays, JobNo to JobNo array, etc. the following code is my attempt, but it doesn't store the values (crashes at toast because it says no data in array).
thanks
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Spinner staticSpinner = (Spinner) findViewById(R.id.static_spinner);
ArrayList<Integer> JobNo = new ArrayList<>();
ArrayList<Integer> JobTime= new ArrayList<>();
ArrayList<String> JobDate= new ArrayList<>();
ArrayList<Integer> WorkerTime= new ArrayList<>();
ArrayList<Integer> JobTimeError = new ArrayList<>();
try {
JSONObject json = new JSONObject(loadJSONFromAsset());
JSONArray jArray = json.getJSONArray("Data");
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
int JobN = json_data.getInt("JobNo");
int JobT = json_data.getInt("JobTime");
String JobD = json_data.getString("JobDate");
int WorkT = json_data.getInt("WorkerTime");
int JobTE = json_data.getInt("JobTimeError");
JobNo.add(JobN);
JobTime.add(JobT);
JobDate.add(JobD);
WorkerTime.add(WorkT);
JobTimeError.add(JobTE);
}
}
catch (JSONException e) {
e.printStackTrace();
}
Toast.makeText(this,
JobDate.get(1),
Toast.LENGTH_LONG).show();
}
public String loadJSONFromAsset() {
String json = null;
try {
InputStream is = getAssets().open("convertcsv.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;
}
Your JSON String is not a JSON object, it is a JSON Array, So use:
JSONArray jArray = new JSONArray (loadJSONFromAsset());
I want to get two json array from remote url
I am using AsyncTask to do that but i can't get any data !
#Override
protected Void doInBackground(String... params) {
try {
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
String json = jParser.getJSONFromUrl(params[0]);
// Getting Array of Contacts
data = new JSONArray(json);
JSONArray cities = data.getJSONArray();
// looping through All cities
for (int i = 0; i < cities.length(); i++) {
JSONObject e = cities.getJSONObject(i);
String ci_name = e.getString("ct_name");
String ci_web_id = e.getString("ct_id");
db.addCity(ci_name, ci_web_id);
db.closeDatabase();
}
JSONArray districts = data.getJSONArray(1);
// looping through All districts
for (int i = 0; i < districts.length(); i++) {
JSONObject e = districts.getJSONObject(i);
String di_name = e.getString("ar_name");
String di_web_id = e.getString("ar_id");
db.addDistrict(di_name, di_web_id);
db.closeDatabase();
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
The return data is like that :
{"city":[
{"ct_id":"1432","ct_name":"\u062e\u0645\u064a\u0633 \u0645\u0634\u064a\u0637","ct_hide":"0","ct_ord":"0","ct_created":"0"},
{"ct_id":"1434","ct_name":"\u0639\u0633\u064a\u0631","ct_hide":"0","ct_ord":"0","ct_created":"0"},{"ct_id":"1435","ct_name":"\u0627\u0644\u0645\u0646\u0637\u0642\u0629 \u0627\u0644\u0634\u0631\u0642\u064a\u0629","ct_hide":"0","ct_ord":"0","ct_created":"0"}
], "area":[
{"ar_id":"1422","ar_name":"\u0627\u0644\u0645\u062f\u064a\u0646\u0629 \u0627\u0644\u0645\u0646\u0648\u0631\u0647","ar_hide":null,"ar_ord":null,"ar_created":null}, {"ar_id":"1433","ar_name":"\u0646\u062c\u0631\u0627\u0646","ar_hide":null,"ar_ord":null,"ar_created":null}]
}
Your json is a JSONObject not a JSONarray.
This
data = new JSONArray(json);
is wrong.
{ // json object node
"city": [ // json array city
{ // json object
"ct_id": "1432",
"ct_name": "خميس مشيط",
"ct_hide": "0",
"ct_ord": "0",
"ct_created": "0"
},
{
"ct_id": "1434",
"ct_name": "عسير",
"ct_hide": "0",
"ct_ord": "0",
"ct_created": "0"
},
{
"ct_id": "1435",
"ct_name": "المنطقة الشرقية",
"ct_hide": "0",
"ct_ord": "0",
"ct_created": "0"
}
],
"area": [ // json array area
{
"ar_id": "1422",
"ar_name": "المدينة المنوره",
"ar_hide": null,
"ar_ord": null,
"ar_created": null
},
{
"ar_id": "1433",
"ar_name": "نجران",
"ar_hide": null,
"ar_ord": null,
"ar_created": null
}
]
}
To parse
JSONObject jb = new JSONObject(json);
JSONArray city = jb.getJSONArray("city");
for(int i=0;i<city.length();i++)
{
JSONObject jb1 = city.getJSONObject(i);
String id = jb1.getString("ct_id");
String name = jb1.getString("ct_name");
String hide = jb1.getString("ct_hide");
String ord = jb1.getString("ct_ord");
String created = jb1.getString("ct_ord");
Log.i("city id is",id);
}
JSONArray area = jb.getJSONArray("area");
for(int i=0;i<area.length();i++)
{
JSONObject jb1 = area.getJSONObject(i);
String id = jb1.getString("ar_id");
String name = jb1.getString("ar_name");
String hide = jb1.getString("ar_hide");
String ord = jb1.getString("ar_ord");
String created = jb1.getString("ar_ord");
Log.i("Area id is",id);
}
You could also consider using gson to parse json to java objects
http://code.google.com/p/google-gson/
I don't see any request to remote url. How do you get data from your server?
Generally, it looks like this:
public void execute() {
final AndroidHttpClient client = AndroidHttpClient.newInstance("TAG");
try {
HttpUriRequest request = getRequest();
HttpResponse response = client.execute(request);
final int code = response.getStatusLine().getStatusCode();
Log.d("TAG", "Server returns " + code);
if (code == HttpStatus.SC_OK) {
String json = EntityUtils.toString(response.getEntity());
handleResult(json);
}
} catch (IOException e) {
Log.e("TAG", "Failed to execute response", e);
}
}
private void handleResult(String json) {
try {
JSONObject jObject = new JSONObject(json);//your response is not an array
JSONArray content = jObject.getJSONArray("city")
final int count = content.length();
for (int i = 0; i < count; i++) {
JSONObject city = content.getJSONObject(i);
Log.d("TAG", city.getString("ct_id"));
}
} catch (JSONException e) {
Log.e("TAG", "Failed to obtain json", e);
}
}
How i can convert my code into "utf-8"?i have a text file which name is "textarabics.txt"
and this text file contains utf-8 characters..below is my code please suggest me how i can convert into utf-8?
try {
File yourFile = new File(Environment.getExternalStorageDirectory(), "textarabics.txt");
FileInputStream stream = new FileInputStream(yourFile);
String jsonStr = null;
try {
FileChannel fc = stream.getChannel();
MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size());
jsonStr = Charset.defaultCharset().decode(bb).toString();
Log.d("Noga Store", "jString = " + jsonStr);
}
finally {
stream.close();
}
Log.d("Noga Store", "jString = " + jsonStr);
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting data JSON Array nodes
JSONArray data = jsonObj.getJSONArray("data");
// looping through All nodes
for (int i = 0; i < data.length(); i++) {
JSONObject c = data.getJSONObject(i);
String id = c.getString("id");
String title = c.getString("title");
// String duration = c.getString("duration");
int duration = c.getInt("duration");
// tmp hashmap for single node
/* HashMap<String, String> parsedData = new HashMap<String, String>();
// adding each child node to HashMap key => value
parsedData.put("id", id);
parsedData.put("title", title);
parsedData.put("duration", duration);*/
textnames.add(title);
textduration.add(duration);
// textnames.add(duration);
// do what do you want on your interface
}
} catch (Exception e) {
e.printStackTrace();
}
This is my "textarabics.txt" file
{
"data": [
{
"id": "1",
"title": "تخطي نوجا نوجا أخبار واستعراض السوق",
"duration": 10
},
{
"id": "2",
"title": "أحدث نوجا الأخبار وآخر المستجدات",
"duration": 3
},
{
"id": "3",
"title": "نوجا الأخبار وآخر المستجدات",
"duration": 5
},
{
"id": "4",
"title": "لا تحتوي على تطبيقات وجد نوع الكلمة",
"duration": 7
},
{
"id": "5",
"title": "تحتاج إلى إعادة تشغيل التطبيق لاتخاذ تغييرات الخط. هل تريد إعادة التشغيل الآن",
"duration": 4
}
]
}
Instead of using Charset.defaultCharset() you can use Charset.forName("UTF-8"). Also you are missing a JSONTokener that you should use with your input. This is based on your code:
try {
File yourFile = new File(Environment.getExternalStorageDirectory(), "textarabics.txt");
FileInputStream stream = new FileInputStream(yourFile);
String jsonStr = null;
try {
FileChannel fc = stream.getChannel();
MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size());
jsonStr = Charset.forName("UTF-8").decode(bb).toString();
Log.d("Noga Store", "jString = " + jsonStr);
}
finally {
stream.close();
}
Log.d("Noga Store", "jString = " + jsonStr);
// A JSONTokener is needed in order to use JSONObject correctly
JSONTokener jsonTokener = new JSONTokener(jsonStr);
// Pass a JSONTokener to the JSONObject constructor
JSONObject jsonObj = new JSONObject(jsonTokener);
// Getting data JSON Array nodes
JSONArray data = jsonObj.getJSONArray("data");
// looping through All nodes
for (int i = 0; i < data.length(); i++) {
JSONObject c = data.getJSONObject(i);
String id = c.getString("id");
String title = c.getString("title");
// String duration = c.getString("duration");
int duration = c.getInt("duration");
// tmp hashmap for single node
/* HashMap<String, String> parsedData = new HashMap<String, String>();
// adding each child node to HashMap key => value
parsedData.put("id", id);
parsedData.put("title", title);
parsedData.put("duration", duration);*/
textnames.add(title);
textduration.add(duration);
// textnames.add(duration);
// do what do you want on your interface
}
} catch (Exception e) {
e.printStackTrace();
}
A more efficient way of dealing with the file would be to wrap the FileInputStream in a InputStreamReader and using InputStreamReader with charset constructor appending the characters to read to a StringBuffer.
Another solution - working on Android 11+ is
try {
File yourFile = new File(Environment.getExternalStorageDirectory(), "textarabics.txt");
FileInputStream stream = new FileInputStream(yourFile);
InputStreamReader reader = new InputStreamReader(stream, "UTF-8");
try {
JsonReader jsonReader = new JsonReader(reader);
jsonReader.beginObject();
jsonReader.nextName();
jsonReader.beginArray();
while (jsonReader.hasNext()) {
jsonReader.beginObject();
while (jsonReader.hasNext()) {
String name = jsonReader.nextName();
if (name.equalsIgnoreCase("id")) {
String id = jsonReader.nextString();
// use the id parameter in some way
System.out.println("id = " + id);
}
if (name.equalsIgnoreCase("title")) {
String title = jsonReader.nextString();
// use the title parameter in some way
System.out.println("title = " + title);
}
if (name.equalsIgnoreCase("duration")) {
// use the duration parameter in some way
int duration = jsonReader.nextInt();
System.out.println("duration = " + duration);
}
}
jsonReader.endObject();
}
jsonReader.endArray();
jsonReader.endObject();
} finally {
try {
if (reader != null) {
reader.close();
}
reader = null;
} catch (Exception e) {
// TODO: handle exception
}
try {
if(stream != null) {
stream.close();
}
stream = null;
} catch (Exception e) {
// TODO: handle exception
}
}
} catch (Exception e) {
e.printStackTrace();
}
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