Parse json array android - java

Hi i'm trying to parse json array from this url. The json array looks like this.
[
{
"id":1,
"introtext":"\u041b\u0438\u043c\u0443\u0437\u0438\u043d\u0430\u0442\u0430 \u0435 \u043e\u0434 \u0430\u043c\u0435\u0440\u0438\u043a\u0430\u043d\u0441\u043a\u043e \u043f\u0440\u043e\u0438\u0437\u0432\u043e\u0434\u0441\u0442\u0432\u043e \u0432\u043e \u0431\u0435\u043b\u0430 \u0431\u043e\u0458\u0430 \u0434\u043e\u043b\u0433\u0430 \u043e\u043a\u043e\u043b\u0443 8,5 \u043c\u0435\u0442\u0440\u0438. \u041e\u043f\u0440\u0435\u043c\u0435\u043d\u0430 \u0435 \u0441\u043e \u043a\u043b\u0438\u043c\u0430 \u0440\u0435\u0434, \u0422\u0412, \u0414\u0412\u0414 \u0438 \u0431\u0430\u0440. \u041c\u043e\u0436\u0430\u0442 \u0434\u0430 \u0441\u0435 \u0432\u043e\u0437\u0430\u0442 \u0434\u043e 9 \u043b\u0438\u0446\u0430. \u0421\u0435 \u0438\u0437\u043d\u0430\u0458\u043c\u0443\u0432\u0430 \u0441\u043e \u043d\u0430\u0448 \u0448\u043e\u0444\u0435\u0440.\n{AdmirorGallery}..\/katalog\/prevoz\/limo-servis-jasmina\/linkoln\/{\/AdmirorGallery}\n\u00a0",
"image":"http:\/\/zasvadba.mk\/media\/k2\/items\/cache\/787ae9ec9023a82f5aa7e4c1a64f73cb_S.jpg",
"title":"\u041b\u0438\u043c\u0443\u0437\u0438\u043d\u0430 \u041b\u0438\u043d\u043a\u043e\u043b\u043d",
"catid":"20",
"alias":"\u043b\u0438\u043c\u0443\u0437\u0438\u043d\u0430-\u043b\u0438\u043d\u043a\u043e\u043b\u043d-\u043b\u0438\u043c\u043e-\u0441\u0435\u0440\u0432\u0438\u0441-\u0458\u0430\u0441\u043c\u0438\u043d\u0430"
}
]
I'm doing this in my java class
try {
JSONfunctions j=new JSONfunctions();
JSONObject json = j.getJSONfromURL(url);
Log.i("log_tag", json.toString());
String jsonvalues = json.getString("id");
Log.i("DARE", jsonvalues);
}
catch (Exception ex)
{
Log.e("log_tag", "Error getJSONfromURL "+ex.toString());
}
}
But it doesn't work, can anybody help me parse my json array

you will need to make two changes in your current code according to string u have posted here for parsing as Json :
First : change the return type of getJSONfromURL method to JSONArray and return JSONArray from it instead of JSONObject
For example :
public JSONArray getJSONfromURL(String url){
String str_response="response from server";
// convert response to JSONArray
JSONArray json_Array=new JSONArray(str_response);
return json_Array; //<< retun jsonArray
}
Second : change your code as for getting value from JsonArray :
try {
JSONfunctions j=new JSONfunctions();
JSONArray jArray = j.getJSONfromURL(url);
Log.i("log_tag", jArray.toString());
for(int i=0;i<jArray.length();i++){
JSONObject json_data = jArray.getJSONObject(i);
String jsonvalues = json_data.getString("id");
// .. get all value here
Log.i("DARE", jsonvalues);
}
}
catch (Exception ex)
{
Log.e("log_tag", "Error getJSONfromURL "+ex.toString());
}

Of course it doesn't work! You should use json.getJSONArray(...) method for parsing arrays in Json :)

You can Easily do it using gson library.
Here is the code sample:
Your Entity Class will like:
public class ResponseEntity {
#SerializedName("id")
public int id;
#SerializedName("introtext")
public String introtext;
#SerializedName("image")
public String image;
#SerializedName("title")
public String title;
#SerializedName("catid")
public String catid;
#SerializedName("alias")
public String alias;
}
Now Convert this json Array using GSON library.
Gson gson=new Gson();
ResponseEntity[] entities = gson.fromJson(yourResponseAsString.toString(),
ResponseEntity[].class);
Now you have the entity array at entities.
Thanks.

Related

How to read [JSONArray[JSONArray]] responses from Volley service

I have a jsonArray response. I need to read this response which contains with 3 jsonArrays.
This is the json response. This is a GET request and send by Volley request.
[
"0x9000",
[
[
"D3521",
"abc"
],
[
"D4212",
"def"
],
[
"D2715",
"hij ."
],
[
"D2366",
"klm"
],
[
"D3660",
"nopq"
]
]
]
Here is the code that I have tried I'm sending a string request.
try{
RequestQueue MyRequestQueue = Volley.newRequestQueue(this);
final String endpoint = "getdoctors";
final String url = SettingsConfig.IP + endpoint;
StringRequest MyStringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
android.util.Log.d("print response",response);
try {
JSONArray jsonArray = new JSONArray(response);
for (int i=0; i<jsonArray.length(); i++){
JSONArray dataArray = (JSONArray) jsonArray;
String code = dataArray.getString(i);
}
} catch (JSONException e) {
e.printStackTrace();
Log.e("Provider Inquiry","JSON error:" + e.getMessage());
Intent intent = new Intent(EChannellingInfoActivity.this,MainMenuActivity.class);
startActivity(intent);
finish();
}
}
}, new Response.ErrorListener() { //Create an error listener to handle errors appropriately.
#Override
public void onErrorResponse(VolleyError error) {
android.util.Log.d("print error", error.toString());
//This code is executed if there is an error.
}
});
MyStringRequest.setRetryPolicy(new DefaultRetryPolicy(0, 0, DefaultRetryPolicy.DEFAULT_TIMEOUT_MS));
MyRequestQueue.add(MyStringRequest);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
There are 3 jsonArrays in this response. How can I categorize/read them one by one.
First Create a class which contains the inner instance
public class InnerObj
{
String id;
String name;
}
Then Create the Class of outer object using the inner object
public class OuterObj
{
String size;
InnerObj values[];
}
Now you can use the OuterObj class as the responseType map it to the response from volley
I want to parse the following JSON file but is starting with [ indicating to me that is an array.
When JSON string starting with [ means the string is JSONArray
how to modify the parser to parse this file?
1. Convert JSON String to JSONArray instead of JSONObject:
JSONArray jsonArray = new JSONArray(json);
2. Change return type of getJSONFromUrl method to JSONArray from JSONObject
3. In doInBackground get response from getJSONFromUrl method in JSONArray:
JSONArray jsonArray = jParser.getJSONFromUrl(URL);
Here is further answers LINK
Here is you can parse your JSON array
JSONArray jsonArray = new JSONArray(response);
String str = (String) jsonArray.get(0);
JSONArray arrayTwo = jsonArray.getJSONArray(1);
for (int i=0; i<arrayTwo.length(); i++){
JSONArray dataArray = arrayTwo.getJSONArray(i);
String code = dataArray.getString(i);
}

Android: How to get JSON object keys from this json:

This is the JSON array:
{
"server_response": [{
"Total": "135",
"Paid": "105",
"Rest": "30"
}]
}
So, how can i get the object names? I want to put them in separate TextView.
Thanks.
Put this out side everything. I mean outside onCreate() and all.
private <T> Iterable<T> iterate(final Iterator<T> i){
return new Iterable<T>() {
#Override
public Iterator<T> iterator() {
return i;
}
};
}
For getting the names of objects :
try
{
JSONObject jsonObject = new JSONObject("{" +"\"server_response\": [{" +"\"Total\": \"135\"," +"\"Paid\": \"105\"," +"\"Rest\": \"30\"" +"}]"+"}";);
JSONArray jsonArray = jsonObject.getJSONArray("server_response");
JSONObject object = jsonArray.getJSONObject(0);
for (String key : iterate(object.keys()))
{
// here key will be containing your OBJECT NAME YOU CAN SET IT IN TEXTVIEW.
Toast.makeText(HomeActivity.this, ""+key, Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
Hope this helps :)
My suggestion:
Go to this website:
Json to pojo
Get your pojo classes and then use them in Android.
All you need to do is to use Gson.fromGson(params here).
One of your params is the class that you created using the online schema.
You can use jackson ObjectMapper to do this.
public class ServerResponse {
#JsonProperty("Total")
private String total;
#JsonProperty("Paid")
private String paid;
#JsonProperty("Rest")
private String rest;
//getters and setters
//toString()
}
//Now convert json into ServerResponse object
ObjectMapper mapper = new ObjectMapper();
TypeReference<ServerResponse> serverResponse = new TypeReference<ServerResponse>() { };
Object object = mapper.readValue(jsonString, serverResponse);
if (object instanceof ServerResponse) {
return (ServerResponse) object;
}
JSONObject jsonObject = new JSONObject("Your JSON");
int Total = jsonObject.getJSONArray("server_response").getJSONObject(0).getInt("Total");
int Paid = jsonObject.getJSONArray("server_response").getJSONObject(0).getInt("Paid");
int Rest = jsonObject.getJSONArray("server_response").getJSONObject(0).getInt("Rest");

can't fetch json object with correct format

Suppose I am fetching from an api some json array as so
[{"id":1,"title":"title","description":"description","vote":null,"created_at":"2013-11-12T21:08:10.922Z","updated_at":"2013-11-12T21:08:10.922Z"}]
I want to retrieve this json as an Some object from URL_Some url
public class Some implements Serializable {
private String id;
private String title;
private String description;
private String vote;
private String created_at;
private String updated_at;
}//with all getters and setters
.
public List<Some> getSome() throws IOException {
try {
HttpRequest request = execute(HttpRequest.get(URL_Some));
SomeWrapper response = fromJson(request, SomeWrapper.class);
Field[] fields = response.getClass().getDeclaredFields();
for (int i=0; i<fields.length; i++)
{
try {
Log.i("TAG", (String) fields[i].get(response));
} catch (IllegalAccessException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
Log.i("TAG", fields[i].getName());
}
if (response != null && response.results != null)
return response.results;
return Collections.emptyList();
} catch (HttpRequestException e) {
throw e.getCause();
}
}
and SomeWrapper is simply
private static class SomeWrapper {
private List<Some> results;
}
The problem is that I keep on getting this message
java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY
PS : I use
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonParseException;
Your json should actually be like this:
{"results": [{"id":1,"title":"title","description":"description","vote":null,"created_at":"2013-11-12T21:08:10.922Z","updated_at":"2013-11-12T21:08:10.922Z"}]}
Gson will try to parse the json and create a SomeWrapper object. This alone tells Gson he will wait for a json with this format {...} since he's expecting an object. However you passed an array instead, that's why it complains about expecting BEGIN_OBJECT ({) but getting BEGIN_ARRAY instead ([). After that, it will expect this json object to have a results field, which will hold an array of objects.
You can create List<Some> directly without the need of a wrapper class however. To do so do this instead:
Type type= new TypeToken<List<Some>>() {}.getType();
List<Some> someList = new GsonBuilder().create().fromJson(jsonArray, type);
In this case, you can use the original json array you posted.
The JSON you posted is a JSON array, which is indicated by the squared brackets around it: [ ].
You'd have to read the first object from the JSON array.
I personally use the org.json packages for Android JSON and parse my JSON in a manner like this:
private void parseJSON(String jsonString) {
JSONArray json;
try {
json = new JSONArray(jsonString);
JSONObject jsonObject = jsonArray.getJSONObject(0);
String id = jsonObject.getString("id");
} catch (JSONException jsonex) {
jsonex.printStackTrace();
}
}
If you've got multiple JSON objects in your array you can iterate over them by using a simple for loop (not for each!)

Can not convert json string to object

I'm constructiong a JSONObject in my javascript and then sending it as a string to my servlet using this code:
insertDtls = function() {
var jsonObj = [];
jsonObj.push({location: this.location()});
jsonObj.push({value: this.value()});
jsonObj.push({coverage: this.coverage()});
jsonObj.push({validPeriod: this.collateralValidPer()});
jsonObj.push({description: this.description()});
var b = JSON.stringify(jsonObj);
console.log(b.toString());
$.ajax({
url:"/HDSWFHub/AppProxy",
type: 'GET',
data: $.extend({WrJOB: "insertDtls", mainData: b}, tJS.getCommonPostData()),
dataType: "json",
success: function(responseText, status, xhr){
updateViewModel(responseText);
},
error: function(jqXHR, textStatus, error){
tJS.manageError(jqXHR);
}
});
},
The string looks like:
[{"location":"Boston"},{"value":"5"},{"coverage":"15"},{"validPeriod":"08/05/2013"},{"description":"test description"}] and the servlet receives it without a problem.
Then I'm getting this in my servlet:
String step = request.getParameter("mainData");
JSONObject jsonObj = new JSONObject();
final JSONObject obj = new JSONObject();
System.out.println(step);
try {
obj.put("viewModel", "index");
obj.put("WrSESSIONTICKET", sessionTicket);
response.getWriter().print(obj.toString());
} catch (final Exception e) {
logException(request, response, e, true);
}
I'm trying to convert the JSON string back to object in the servlet in order to be able to loop trough the items, or to get the needed one. The library I'm using is org.json
I have tired:
JSONObject jsonObj = new JSONObject(step);
Without any success. Just got this error:
Unhandled exception type JSONException
I don't know what is happening. Maybe I'm too tired already. I'm sure that I'm missing something really small, but I'm unable to spot it.
I know that it has been asked hundreds of times. I know that I will get tons of downvotes, but I was unable to find an answer for my issue.
I tried the string you posted in your comment and it works fine. Here is the full code:
import org.json.JSONArray;
import org.json.JSONException;
public class jsonArray {
public static void main(String[] args) {
String text = "[{\"location\":\"Boston\"},{\"value\":\"5\"},{\"coverage\":\"15\"},{\"validPeriod\":\"08/05/2013\"},{\"description\":\"test description\"}]";
try {
JSONArray jsonArray = new JSONArray(text);
System.out.println(jsonArray.toString());
} catch (JSONException e) {
e.printStackTrace();
}
}
}
p.s. I am using org.json-20120521.jar library
Here your json String is converted to JSONObject .
In your case its not happening because [] brackets denotes Array. so first it is Array and then {} JSONObject in case of your String.
import org.json.JSONArray;
import org.json.JSONObject;
public class Test {
static String str = "[{\"location\":\"Boston\"},{\"value\":\"5\"},{\"coverage\":\"15\"},{\"validPeriod\":\"08/05/2013\"},{\"description\":\"test description\"}]";
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
JSONArray jsonArr = new JSONArray(str);
System.out.println("JSON ARRAY IS : ");
System.out.println(jsonArr.toString());
for(int i =0 ; i<jsonArr.length() ;i++ ){
JSONObject jsonObj = jsonArr.getJSONObject(i);
System.out.println();
System.out.println(i+" JSON OBJECT IS : ");
System.out.println(jsonObj.toString());
}
} catch (org.json.JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
OUTPUT
JSON ARRAY IS :
[{"location":"Boston"},{"value":"5"},{"coverage":"15"},{"validPeriod":"08/05/2013"},{"description":"test description"}]
0 JSON OBJECT IS :
{"location":"Boston"}
1 JSON OBJECT IS :
{"value":"5"}
2 JSON OBJECT IS :
{"coverage":"15"}
3 JSON OBJECT IS :
{"validPeriod":"08/05/2013"}
4 JSON OBJECT IS :
{"description":"test description"}

Java JsonObject array value to key

I'm new to java so this is a bit confusing
I want to get json formatted string
The result I want is
{ "user": [ "name", "lamis" ] }
What I'm currently doing is this :
JSONObject json = new JSONObject();
json.put("name", "Lamis");
System.out.println(json.toString());
And I'm getting this result
{"name":"Lamis"}
I tried this but it didnt work
json.put("user", json.put("name", "Lamis"));
Try this:
JSONObject json = new JSONObject();
json.put("user", new JSONArray(new Object[] { "name", "Lamis"} ));
System.out.println(json.toString());
However the "wrong" result you showed would be a more natural mapping of "there's a user with the name "lamis" than the "correct" result.
Why do you think the "correct" result is better?
Another way of doing it is to use a JSONArray for presenting a list
JSONArray arr = new JSONArray();
arr.put("name");
arr.put("lamis");
JSONObject json = new JSONObject();
json.put("user", arr);
System.out.println(json); //{ "user": [ "name", "lamis" ] }
Probably what you are after is different than what you think you need;
You should have a separate 'User' object to hold all properties like name, age etc etc.
And then that object should have a method giving you the Json representation of the object...
You can check the code below;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;
public class User {
String name;
Integer age;
public User(String name, Integer age) {
this.name = name;
this.age = age;
}
public JSONObject toJson() {
try {
JSONObject json = new JSONObject();
json.put("name", name);
json.put("age", age);
return json;
} catch (JSONException e) {
e.printStackTrace();
return null;
}
}
public static void main(String[] args) {
User lamis = new User("lamis", 23);
System.out.println(lamis.toJson());
}
}

Categories

Resources