Android - Parse PHP json_encode to Java - java

String json_string_from_server = "{\"test1\":\"test1_value\",\"test2\":\"test2_value\"}";
how to loop the JSON and print all the keys and values.

You can simply parse the Json string as below -
String json_string_from_server = "{\"test1\":\"test1_value\",\"test2\":\"test2_value\"}";
JSONObject jObj = new JSONObject(json_string_from_server);
String val_Test1 = jObj.getString("test1");
String val_Test2 = jObj.getString("test2");
case 2:
String json_string_from_server = "{
"result" : [
{\"test1\":\"test1_values_baru\", \"test2\":\"test2_values\"},
{\"test1\":\"test‌​1_values\", \"test2\":\"test2_values\"}
]
}";
JSONObject jObj = new JSONObject(json_string_from_server);
JSONArray jResultArray = jObj.getJSONArray("result");
for(int i=0; i<jResultArray.length(); i++){
JSONObject jResultObj = jResultArray.getJSONObject(i);
String val_Test1 = jResultObj.getString("test1");
String val_Test2 = jResultObj.getString("test2");
}

Suppose jsonString is a variable in which you get all your json from php. You will need to iterate the array as follows:
JSONArray arr = new JSONArray(JsonString);
for(int i=0; i<= arr.length(); i++)
{
JSONObject obj = arr.get(i);
obj.getString('test1'); // these are your strings
obj.getString('test2');
}

String json_string="[{\"test1\":\"test1_values_baru\",\"test2\":\"test2_values\"},{\"test1\":\"test‌​1_values\",\"test2\":\"test2_values\"}]";
JSONArray jResultArray = new JSONArray(json_string);
for(int i=0; i<jResultArray.length(); i++){
JSONObject jResultObj = jResultArray.getJSONObject(i);
String val_Test1 = jResultObj.getString("test1");
String val_Test2 = jResultObj.getString("test2");
}

Related

want to store multiple JSON objects to jsonArray and get the result as a single string

Here is my code for storing multiple JSON objects into an array and then I want to convert the array into a single string.
String message =null;
JSONObject json = new JSONObject();
json.put("name","student");
json.put("name", "Atal");
json.put("name","Rachit");
JSONArray array = new JSONArray();
for(int i= 0; i<= array.length(); i++) {
array.put(json);
message = array.toJSONString();
}
I want to get the output as a string and store it in a message variable.
String message =null;
JSONObject json = new JSONObject();
json.put("name","student");
json.put("name", "Atal");
json.put("name","Rachit");
JSONArray array = new JSONArray();
//for(int i= 0; i<= array.length(); i++) {
// array.put(json);
// message = array.toJSONString();
//}
array.put(json); //There is a JSON,just put it into the array
message = array.toJSONString();
I was replacing "name" every time I was calling json.put()
String message =null;
JSONObject json = new JSONObject();
json.put("name","Atal");
json.put("class", "10");
json.put("Roll","1035");
JSONArray array = new JSONArray();
array.put(json);
message = array.toJSONString();

How to Get String From Parse JSON without String Id in Android Studio

How do I get a string from Parse JSON with data like below?
My Data JSON :
[
[
"John Gorman",
"3344764667200003",
"Student",
"2018-08-09 08:21:30.807"
],
[
"Andy William",
"3403032311690003",
"Student",
"2018-08-09 08:21:30.807"
],
[
"Thomas Endry",
"3408932311690078",
"Student",
"2018-08-09 08:21:30.807"
],
[
"Robet Calm",
"3403077711690890",
"Student",
"2018-08-09 08:21:30.807"
]
]
I use the code below, then to get the string what I have to do, I really don't understand, if there is help, I really need to thank you.
try {
JSONObject object = new JSONObject(result);
JSONArray jsonArray = object.getJSONArray("");
//JSONArray jsonArray = new JSONArray(result);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject c = jsonArray.getJSONObject(i);
String name = c.getString("What should I write here");
System.out.println(c.getString(""));
}
I want to get the string from Parse JSON that I have
How do I get a string for listview, for example:
John Gorman
3344764667200003
Student
Andy William
3403032311690003
Student
Thomas Endry
3408932311690078
Student
Robet Calm
3403077711690890
Student
A couple of things are wrong with the posted code. See my comments inline:
JSONObject object = new JSONObject(result);
^^^^^^^^^^^^^^^^^^^^^^
the content of result is not an object, but an array!
JSONArray jsonArray = object.getJSONArray("");
^^
a proper JSON document had better not have empty keys!
//JSONArray jsonArray = new JSONArray(result);
^^^^^^^^^^^^^^^^^^^^^
this was actually going in the right direction!
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject c = jsonArray.getJSONObject(i);
^^^^^^^^^^^^^^^^^^^^^^^^^^
the i-th element of the array is not an object, but an array!
Fixing the issues above:
JSONArray jsonArray = new JSONArray(result);
for (int i = 0; i < jsonArray.length(); i++) {
JSONArray subArray = jsonArray.getJSONArray(i);
for (int j = 0; j < subArray.length(); j++) {
System.out.println(subArray.getString(j));
}
System.out.println();
}
You are receiving a JSONArray not object so use the below code.
for(int i=0;i<jsonarray.length();i++){
JSONArray array=jsonarray.getJSONArray(i);
for(int j=0;j<array.length();j++){
Log.d(TAG,array.getString(j));
}
}
You can do something like this:
try {
JSONObject object = new JSONObject(result);
JSONArray jsonArray = object.getJSONArray("");
//JSONArray jsonArray = new JSONArray(result);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject c = jsonArray.getJSONObject(i);
String name = c.getString(0);
String id = c.getString(1);
String student = c.getString(2);
// and so on ... This index refers to the index number on the string inside json object
System.out.println(name);
}
Hope this answers your query.
Following method will construct a list of string from the given Json. You can pass that list in the adapter of the list view.
public List<String> getList (String result) throws JSONException {
List<String> list = new LinkedList<>();
JSONArray jsonArray = new JSONArray(result);
for (int i = 0; i < jsonArray.length(); i++) {
JSONArray arr = jsonArray.getJSONArray(i);
StringBuilder sb = new StringBuilder();
for(int j=0;j<arr.length(); j++) {
sb.append(arr.getString(j));
if(j<arr.length()-1) sb.append("\n");
}
list.add(sb.toString());
}
return list;
}

at 0 of type java.lang.String cannot be converted to JSONArray

I am facing this exception at 0 of type java.lang.String cannot be converted to JSONArray don't know why? i have use this before in different work didn't get this exception
List<NameValuePair> pair = new ArrayList<>();
pair.add(new BasicNameValuePair("id", String.valueOf(getitemno)));
json = JSONParser.makeHttpRequest("http://192.168.1.51:80/StopViewApi/index.php","POST",pair);
Log.d("Route Response", json.toString());
int success = 0;
try {
success = json.getInt(TAG_SUCCESS);
Routearrray = new ArrayList<String>();
} catch (JSONException e) {
e.printStackTrace();
}
try {
if (success == 1) {
JSONArray jsonarray;
json = new JSONObject(JSONParser.Result);
JSONArray jArray = json.getJSONArray("data");
for (int i = 0; i <= jArray.length(); i++) {
jsonarray = jArray.getJSONArray(i);
Stopnames = jsonarray.getString(0);
Counter++;
if (Counter <=jArray.length()) {
//Routearrray.add(Stopnames);
Log.d("Stop name:", Stopnames);
//Log.d("Route name:", Routearrray.toString());
} else {
break;
}
}
JSON URL
{
"data":[
"Rawat","Islamabad Mor","Kaak Pull","Lohi Bher","Koral Chowk","Gangal",
"Khana Bridge","Zia Masjid","Kuri Road","Dhok Kala Khan","Faizabad",
"Pirwadhai Mor","Tanki Stop I-8\/4","I-8\/3 Stop","Al Shifa Hospital","AIOU",
"Zero Point","Children Hospital","F-8\/4","Ali Hospital"
],
"success":1,
"status":200,
"status_message":"Login Successfull"
}
Error: at Line
jsonarray = jArray.getJSONArray(i);
From your JSON, jArray is a array of String and not an array of JSONArray.
Replace:
jsonarray = jArray.getJSONArray(i);
Stopnames = jsonarray.getString(0);
with:
Stopnames = jArray.getString(i);
the for loop should be
for (int i = 0; i < jArray.length(); i++) {
You're trying to parse String values as JSONArray. jArray is an array of Strings, not JSONArrays, so all you need to do is just extract the String values from it.
JSONArray jArray = json.getJSONArray("data");
// You already have a JSONArray, now all you need to do is extract String values from it
for (int i = 0; i <= jArray.length(); i++) {
Log.d("Stopnames: " , jArray.getString(i));
....
}
Thats because you "data" is of type json array. whats inside "data" is not a jsonarray, they are just jsonstrings.
change the following lines
jsonarray = jArray.getJSONArray(i);
Stopnames = jsonarray.getString(0);
to
stopnames += jArray.getString(i);
You are trying to get jsonarray from jsonarray, while the json array contains json objects. try this
JSONObject jsonObject = jsonArray.getJSONObject(i)
Stopnames = jsonObject.getString(Integer.toString(i))

How to parse JSON Array of String in android

this is the response from the server
{"route":[1,2,3,4,5,6]}
This is my code:
try{
String d = json.getString("route");
}
}catch(JSONException je){
}
and im getting NullPointerException.
please help me.
This is my Server Response, Now Give me the solution
Link -> http://ajax.tpksym.cloudbees.net/route/route14
It should be like:
JSONObject jsonResult = new JSONObject("{\"route\":[1,2,3,4,5,6]}");
JSONArray array = jsonResult.getJSONArray("route");
for (int i = 0; i < array.length(); i++) {
int data = array.getInt(i);
}
....
try {
String jsonString = "{\"route\":[1,2,3,4,5,6]}";
JSONObject jsonObject = new JSONObject(jsonString);
JSONArray jsonArray = jsonObject.getJSONArray("route");
for (int i = 0; i < jsonArray.length(); i++) {
System.out.println(jsonArray.getInt(i));
}
} catch (JSONException e) {
e.printStackTrace();
}
Hi as yours json is as follows
{
"route": [
1,
2,
3,
4,
5,
6
]
}
so do as follows
String jsondata = "{\"route\":[1,2,3,4,5,6]}";
JSONObject primaryObject = new JSONObject(jsondata);
JSONArray jarray = primaryObject.getJSONArray("route");
for (int i = 0; i < jarray.length(); i++) {
Integer data = jarray.getInt(i);
System.out.println("data=="+data);
}
as you gave the link http://ajax.tpksym.cloudbees.net/route/route14
and data seems there coming as in double i.e. 13.56 etc
so use as follows
String jsondata = "JSON DATA FROM SERVER";
JSONObject primaryObject = new JSONObject(jsondata);
JSONArray jarray = primaryObject.getJSONArray("route");
for (int i = 0; i < jarray.length(); i++) {
Double data = jarray.getDouble(i);
}

Parsing JSON Array within JSON Object

I have some JSON with the following structure:
{"source":[
{"name":"john","age":20},
{"name":"michael","age":25},
{"name":"sara", "age":23}
]
}
I have named this JSON string as mainJSON. I'm trying to access the elements "name" and "age" with the following Java code:
JSONArray jsonMainArr = new JSONArray(mainJSON.getJSONArray("source"));
for (int i = 0; i < jsonMainArr.length(); i++) { // **line 2**
JSONObject childJSONObject = jsonMainArr.getJSONObject(i);
String name = childJSONObject.getString("name");
int age = childJSONObject.getInt("age");
}
I'm being shown the following exception for line number 2:
org.json.JSONException: JSONArray initial value should be a string or collection or array.
Please guide me as to where I'm making the mistake and how to rectify this.
mainJSON.getJSONArray("source") returns a JSONArray, hence you can remove the new JSONArray.
The JSONArray contructor with an object parameter expects it to be a Collection or Array (not JSONArray)
Try this:
JSONArray jsonMainArr = mainJSON.getJSONArray("source");
Your code is fine, just replace the following line:
JSONArray jsonMainArr = new JSONArray(mainJSON.getJSONArray("source"));
with this line:
JSONArray jsonMainArr = mainJSON.getJSONArray("source");
line 2 should be
for (int i = 0; i < jsonMainArr.size(); i++) { // **line 2**
For line 3, I'm having to do
JSONObject childJSONObject = (JSONObject) new JSONParser().parse(jsonMainArr.get(i).toString());
private static String readAll(Reader rd) throws IOException {
StringBuilder sb = new StringBuilder();
int cp;
while ((cp = rd.read()) != -1) {
sb.append((char) cp);
}
return sb.toString();
}
String jsonText = readAll(inputofyourjsonstream);
JSONObject json = new JSONObject(jsonText);
JSONArray arr = json.getJSONArray("sources");
Your arr would looks like: [
{
"id":1001,
"name":"jhon"
},
{
"id":1002,
"name":"jhon"
}
]
You can use:
arr.getJSONObject(index)
to get the objects inside of the array.
This could be an answer to your question:
JSONArray msg1 = (JSONArray) json.get("source");
for(int i = 0; i < msg1.length(); i++){
String name = msg1.getString("name");
int age = msg1.getInt("age");
}

Categories