I am getting this trouble?
[
{
"username": "apap",
"status": "",
"log": "",
"email": "apap#gmail.com",
"lat": "",
"dob": "5-11-1986"
},
{
"username": "apapp",
"status": "",
"log": "",
"email": "apapp#gmail.com",
"lat": "",
"dob": "5-11-1986"
}
],
"returncode": "0"
}
Error parsing data org.json.JSONException: Value {"incircle": at response of type org.json.JSONObject cannot be converted to JSONArray
For extracting incircle array value,I am writing following code:
public class MainActivity extends Activity {
TextView username;
TextView email;
TextView dob;
TextView lat;
TextView log;
ListView listView;
ArrayList<HashMap<String,String>> jsonlist;
JsonAdapter objAdapter;
Context ctx;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
listView = (ListView) findViewById(R.id.listView);
jsonlist = new ArrayList<HashMap<String,String>>();
JSONObject json = JSONfunctions
.getJSONfromURL("http://www.railsboxtech.com/flirtalert/alluser.php");
try {
JSONArray flirt = json.getJSONArray("response");
Toast.makeText(MainActivity.this, "namr", Toast.LENGTH_LONG).show();
for (int i = 0; i < flirt.length(); i++) {
JSONObject ei = flirt.getJSONObject(i);
JSONArray eie = ei.getJSONArray("incircle");
for (int j = 0; j < eie.length(); j++) {
JSONObject e = eie.getJSONObject(j);
HashMap<String, String> map = new HashMap<String, String>();
map.put("User",e.getString("username"));
map.put("Email",e.getString("email"));
map.put("dob",e.getString("dob"));
map.put("lat",e.getString("lat"));
map.put("log",e.getString("log"));
jsonlist.add(map);
}
}
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
ListAdapter adapter = new SimpleAdapter(this, jsonlist, R.layout.user_list,
new String[] { "User", "Email","dob","lat","log"}, new int[] {
R.id.username, R.id.email, R.id.dob, R.id.lat, R.id.log});
listView.setAdapter(adapter);
listView.setTextFilterEnabled(true);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
When you retrieve the elements of the array with this line
JSONArray ja1= eie.getJSONArray(j);
You require the elements to be arrays themselfs, however, in your input the elements are objects.
Since the input has only one array but your code assumes two nested arrays, you probably want something like:
JSONObject json = JSONfunctions
.getJSONfromURL("http://www.railsboxtech.com/flirtalert/alluser.php");
try {
JSONObject ei = json.getJSONObject("response");
JSONArray eie = ei.getJSONArray("incircle");
for (int j = 0; j < eie.length(); j++) {
JSONObject e = eie.getJSONObject(j);
HashMap<String, String> map = new HashMap<String, String>();
map.put("User",e.getString("username"));
map.put("Email",e.getString("email"));
map.put("dob",e.getString("dob"));
map.put("lat",e.getString("lat"));
map.put("log",e.getString("log"));
jsonlist.add(map);
}
} catch ...
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'm trying to get a JSON array for ListView on Android, but I couldn't so far.
My JSON is like this
[
{
"iD":1,
"name":"name1"
},
{
"iD":2,
"name":"name2"
},
{
"iD":3,
"name":"name3"
},
{
"iD":4,
"name":"name4"
}
]
Also Try tried this second JSON format
{
"userdata":[
{
"iD":1,
"name":"name1"
},
{
"iD":2,
"name":"name2"
},
{
"iD":3,
"name":"name3"
},
{
"iD":4,
"name":"name4"
}
]
}
And my Java looks like
private void loadIntoListView(String json) throws JSONException {
Log.e("log1 = ", json);
JSONArray jsonArray = new JSONArray(json);
Log.e("log2 = ","5" ); //Integer.toString(jsonArray.length())
String[] heroes = new String[jsonArray.length()];
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject obj = jsonArray.getJSONObject(i);
heroes[i] = obj.getString("name");
}
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, heroes);
listView.setAdapter(arrayAdapter);
}
private void loadIntoListView(String json) throws JSONException {
Log.e("result 2 = ", json);
JSONObject entries = new JSONObject(json);
JSONArray jsonArray = entries.getJSONArray("userdata");
Log.e("length = ","5" ); //Integer.toString(jsonArray.length())
String[] heroes = new String[jsonArray.length()];
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject obj = jsonArray.getJSONObject(i);
heroes[i] = obj.getString("name");
}
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, heroes);
listView.setAdapter(arrayAdapter);
}
I see the first log, but I can't see second. Also, I can't get the names for ListView.
require_once('connection.php');
$heroes = array();
$sql = "SELECT iD, name FROM valTable;";
$stmt = $conn->prepare($sql);
$stmt->execute();
$stmt->bind_result($id, $name);
while($stmt->fetch()){
$temp = [
'iD'=>$id,
'name'=>$name
];
array_push($heroes, $temp);
}
echo json_encode($heroes);
You should use a JSON library such as Gson to parse those objects for your.
Add on your gradle dependencies
implementation 'com.google.code.gson:gson:2.8.5'
You can create objects like
data class JsonRootObject(val userdata: List<User>)
data class User(val iD:Int, val name:String)
And then parse your object
val myParsedObject = Gson().fromJson(jsonString, JsonRootObject::class.java);
Make sure that your field names are the same as your object being parsed, this also means case sensitive. If you want to change their mapping name you might want to use #SerializedName("id") annotation like
class User {
#SerializedName("id")
lateinit var id: Int
#SerializedName("my_name")
lateinit var name: String
}
Consider this answer to your second object
{
"userdata":[
{
"iD":1,
"name":"name1"
},
{
"iD":2,
"name":"name2"
},
{
"iD":3,
"name":"name3"
},
{
"iD":4,
"name":"name4"
}
]
}
and of course, all this is written in Kotlin.
Use try catch instead of throws
try {
JSONArray jsonArray = new JSONArray(json);
Log.e("log2 = ", "5"); //Integer.toString(jsonArray.length())
String[] heroes = new String[jsonArray.length()];
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject obj = jsonArray.getJSONObject(i);
heroes[i] = obj.getString("name");
}
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, heroes);
listView.setAdapter(arrayAdapter);
}
catch (Exception e)
{
Log.e("log3 = ", ""+e);
}
Try first to convert your String json to JSONObject and then convert that JSONObject to JSONArray. See this answer.
-- I know parsing, i have successfully parsed below data, but when web-service is upgraded i need to parse object inside object.
- I tried many example but getting error.
Code for Parsing :
private final String KEY_SUCCESS = "status";
private final String KEY_MSG = "Message";
private final String KEY_MSG1 = "Message";
// private final String KEY_AddressList = "addressList";
private final String KEY_USERINFO = "user_info";
ArrayList<HashMap<String, String>> arraylist;
private final String KEY_DATA = "data";
private final String KEY_USERDATA = "userdata";
public ArrayList<HashMap<String, String>> getList(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
if (jsonObject.getString(KEY_SUCCESS).equals("true")) {
arraylist = new ArrayList<HashMap<String, String>>();
JSONArray jsonArray = jsonObject.getJSONArray("data");
for (int i = 0; i < jsonArray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
JSONObject obj = jsonArray.getJSONObject(i);
// JSONObject job = obj.getJSONObject("User");
Log.d("obj", obj.toString());
String user_id = obj.getString(Constants.Params.ID);
String createdate = obj.getStringAndyConstants.Params.CREATEDDATE);
String postImage = obj.getString(Constants.Params.IMAGE);
map.put(AndyConstants.Params.ID, user_id);
map.put(AndyConstants.Params.CREATEDDATE, createdate);
map.put(AndyConstants.Params.IMAGE, postImage);
JSONObject objectDetails2 = obj.getJSONObject(KEY_DATA);
JSONArray jsonArrayUser = objectDetails2.getJSONArray("userdata");
for (int j = 0; j < jsonArrayUser.length(); j++) {
HashMap<String, String> mapUser = new HashMap<String, String>();
JSONObject businessObject = jsonArrayUser.getJSONObject(j);
Log.d("obj", businessObject.toString());
}
Log.d("map", map.toString());
arraylist.add(map);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return arraylist;
}
Error Log :
org.json.JSONException: No value for data
E/array: []
E/adapter: []
Json :
{
"status": true,
"message": "Successfully add Post",
"data": [{
"user_id": "46",
"image": "",
"createdate": "2016-05-11 06:05:12",
"userdata": {
"first_name": "Alpha",
"last_name": "Gamma",
"image": "http:\/\/abcd.net\/abcd\/uploads\/100520161005191462941615032.jpg"
}
}
You dont need this line
JSONObject objectDetails2 = obj.getJSONObject(KEY_DATA);
and change
JSONArray jsonArrayUser = objectDetails2.getJSONArray("userdata");
to
JSONObject userData = obj.getJSONObject("userdata");
String firstName = userData.getString("first_name");
String lastName = userData.getString("last_name");
As you can see from the JSON
"data":
[{"user_id":"46",
"image":"",
"createdate":"2016-05-11 06:05:12",
"userdata":{"first_name
data is having the object [ which denotes an Array while userData shows a { which is a JSONObject
I notice that your JSON has some errors. is this the complete Json response?
Because JSON response should be something like this:
{
"status": true,
"message": "Successfully add Post",
"data": [{
"user_id": "46",
"image": "",
"createdate": "2016-05-11 06:05:12",
"userdata": {
"first_name": "Alpha",
"last_name": "Gamma",
"image": "http:\/\/abcd.net\/abcd\/uploads\/100520161005191462941615032.jpg"
}
}]
}
You will notice that there is no close for [ after userdata in your Json.
I'm using JSONParser.java to show JSON data from a url
the url and the data are correct, they show some values of JSON (more than one)
but why this show only one value?
ArrayList<HashMap<String, String>> artikelList = new ArrayList<HashMap<String, String>>();
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONFromUrl(ArtikelURL);
try {
artikels = json.getJSONArray(TAG_ARTIKEL);
for(int i = 0; i < artikels.length(); i++){
JSONObject c = artikels.getJSONObject(i);
// Storing each json item in variable
String tanggal = c.getString(TAG_TGL);
String judul = c.getString(TAG_JUDUL);
String kutipan = c.getString(TAG_KUTIPAN);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_TGL, tanggal);
map.put(TAG_JUDUL, judul);
map.put(TAG_KUTIPAN, kutipan);
artikelList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
This is my JSON data:
{
"status":"1",
"total":20,
"artikel":[
{
"tanggal":"2013-08-07",
"judul":"Article One",
"kutipan":"Example of article quote..."
},
{
"tanggal":"2013-07-23",
"judul":"Article Two",
"kutipan":"Example of article quote......"
},
{
"tanggal":"2013-07-22",
"judul":"Article Three",
"kutipan":"Example of article quote......"
},
{
"tanggal":"2013-03-16",
"judul":"Article Four"",
"kutipan":"Example of article quote,..."
}
]
}
Your JSON is invalid, there's an error in your line 22 at 3rd object of your array
"judul":"Article Four"",
Correct JSON is
{
"status": "1",
"total": 20,
"artikel": [
{
"tanggal": "2013-08-07",
"judul": "Article One",
"kutipan": "Example of article quote..."
},
{
"tanggal": "2013-07-23",
"judul": "Article Two",
"kutipan": "Example of article quote......"
},
{
"tanggal": "2013-07-22",
"judul": "Article Three",
"kutipan": "Example of article quote......"
},
{
"tanggal": "2013-03-16",
"judul": "Article Four",
"kutipan": "Exampleofarticlequote,..."
}
]
}
Ok, Now you are getting Network related exception so, solution to this is, you've to use demo code like
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new NetworkThread().execute();
}
class NetworkThread extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... voids) {
ArrayList<HashMap<String, String>> artikelList = new ArrayList<HashMap<String, String>>();
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONFromUrl(ArtikelURL);
try {
JSONArray artikels = json.getJSONArray("artikel");
for(int i = 0; i < artikels.length(); i++){
JSONObject c = artikels.getJSONObject(i);
// Storing each json item in variable
String tanggal = c.getString(TAG_TGL);
String judul = c.getString(TAG_JUDUL);
String kutipan = c.getString(TAG_KUTIPAN);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_TGL, tanggal);
map.put(TAG_JUDUL, judul);
map.put(TAG_KUTIPAN, kutipan);
artikelList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
}
}
Don't forget to add this to AndroidManifest.xml file:
<uses-permission android:name="android.permission.INTERNET"/>
Your JSON Is Invalid But assuming you have an outer Json Array for the JsonObject This implementation would work for your nested Json
ArrayList<HashMap<String, String>> artikelList = new ArrayList<HashMap<String, String>>();
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONFromUrl(ArtikelURL);
try {
JSONArray a = json.getJSONArray(TAG_JSON);
for(int i = 0; i < a.length(); i++){
HashMap<String, String> map = new HashMap<String, String>();
JSONObject c = a.getJSONObject(i);
map.put(TAG_TOTAL, c.getString(TAG_TOTAL));
map.put(TAG_STATUS, c.getString(TAG_STATUS));
artikelList.add(map);
JSONArray akel = e.getJSONArray(artikel);
if(akel != null){
for(int j=0;j<akel.length();j++){
HashMap<String, String> map2 = new HashMap<String, String>();
JSONObject f = akel.getJSONObject(j);
map2.put(TAG_TGL, f.getString(TAG_TGL));
map2.put(TAG_JUDUL, f.getString(TAG_JUDUL));
map2.put(TAG_KUTIPAN, f.getString(TAG_KUTIPAN));
}
}
} catch (JSONException e) {
e.printStackTrace();
}
I need to parse JSON file with multiple arrays.
Array is in format:
{
"List": {
"Something": [
{
"Name": "John",
"phone": "test"
}
]
"SomethingElse": [
{
"Name": "Smith",
"phone": "test"
}
]
}
}
Problem is that i don't know what wold be next array name. It is possible to parse data from all arrays without name of it and without changing structure of it?
Thanks.
JSON
{
"data": {
"current_condition": [
{
"cloudcover": "25",
"humidity": "62",
"observation_time": "04:57 PM",
"precipMM": "0.1",
"pressure": "1025",
"temp_C": "10",
"temp_F": "50",
"visibility": "10",
"weatherCode": "113",
"weatherDesc": [
{
"value": "Clear"
}
]
}
]
}
}
TO GET THE VALUE OF "weatherDesc"
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(MainActivity.this);
// Set progressdialog title
mProgressDialog.setTitle("Android JSON Parse Tutorial");
// Set progressdialog message
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
// Show progressdialog
mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
// Create an array
arraylist = new ArrayList<HashMap<String, String>>();
// Retrieve JSON Objects from the given URL address
jsonobject = JSONfunctions
.getJSONfromURL("http://api.worldweatheronline.com/free/v1/weather.ashx?q=London&format=json&num_of_days=5&key=8mqumbup9fub7bcjtsxbzxx9");
try {
// Locate the array name in JSON
JSONObject on=jsonobject.getJSONObject("data");
jsonarray = on.getJSONArray("current_condition");
for (int i = 0; i < jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
jsonobject = jsonarray.getJSONObject(i);
JSONArray sen1=jsonobject.getJSONArray("weatherDesc");
// Retrive JSON Objects
for(int j=0;j<sen1.length();j++){
jsonobject2 = sen1.getJSONObject(j);
map.put("value0", jsonobject2.getString("value"));
map.put("value1",jsonobject2.getString("value"));
map.put("flag", null);
// Set the JSON Objects into the array
arraylist.add(map);
}
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void args) {
// Locate the listview in listview_main.xml
listview = (ListView) findViewById(R.id.listview);
// Pass the results into ListViewAdapter.java
adapter = new ListViewAdapter(MainActivity.this, arraylist);
// Set the adapter to the ListView
listview.setAdapter(adapter);
// Close the progressdialog
mProgressDialog.dismiss();
}
}
try this
I had write a function to iterate JsonObject recursively without knowing keys name.
private void parseJson(JSONObject data) {
if (data != null) {
Iterator<String> it = data.keys();
while (it.hasNext()) {
String key = it.next();
try {
if (data.get(key) instanceof JSONArray) {
JSONArray arry = data.getJSONArray(key);
int size = arry.length();
for (int i = 0; i < size; i++) {
parseJson(arry.getJSONObject(i));
}
} else if (data.get(key) instanceof JSONObject) {
parseJson(data.getJSONObject(key));
} else {
System.out.println("" + key + " : " + data.optString(key));
}
} catch (Throwable e) {
System.out.println("" + key + " : " + data.optString(key));
e.printStackTrace();
}
}
}
}
There is a comma missing in your JSON after the Something value, but apart from that, you can parse it using any JSON parser.