I have JsonObject
JSON Object
I have method which return JSONArray. I want to pass first field and get only data array. And then cast it to my Array List. I will really appriciated for any suggestion from you.
void getUsersBeacons(){
type = new TypeToken<List<Beacon>>(){}.getType();
JSONArray myReq = new JSONArray(Request.Method.GET, Url + testId + Url2, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try{
JSONArray buffArray = response.getJSONArray(2);
JSONArray bufJsonArray = response.getJSONArray(1);
beaconsList = converter.fromJson(bufJsonArray.toString(), type);
}catch (Exception e){
e.printStackTrace();
}
}
});
VolleySingleton.getInstance(getActivity().getApplicationContext()).addToRequestQueue(myReq);
}
Beacon class:
public class Beacon {
private Object idBeacon;
private String friendlyName;
private String imageUrl;
public Beacon(Object idBeacon, String friendlyName, String imageUrl) {
this.idBeacon = idBeacon;
this.friendlyName = friendlyName;
this.imageUrl = imageUrl;
}
public Object getIdBeacon() {
return idBeacon;
}
public void setIdBeacon(Object idBeacon) {
this.idBeacon = idBeacon;
}
public String getFriendlyName() {
return friendlyName;
}
public void setFriendlyName(String friendlyName) {
this.friendlyName = friendlyName;
}
public String getImageUrl() {
return imageUrl;
}
public void setImageUrl(String imageUrl) {
this.imageUrl = imageUrl;
}
}
If I understand correctly, you better pass in JSONArray instead of string and parse it's contents, like this:
public static List<Beacon> fromJson(JSONArray array)
{
ArrayList<Beacon> res = new ArrayList<>();
for (int i = 0; i < array.length(); ++i)
{
JSONObject beacon = array.getJSONObject(i);
res.add(new Beacon(beacon.getInt("beaconId"), beacon.getString("name"), beacon.getString("imageUrl"))));
}
return res;
}
UPD: in response to your comment, you must use Response.Listener<JSONObject> instead of Response.Listener<JSONArray>, and then do this:
public void onResponse(JSONObject response)
{
JSONArray array = response.getJSONArray("data");
converter.fromJson(array);
}
Related
I am calling Restful service using below code :(Java.net implementation )
StringBuilder responseStrBuilder = new StringBuilder();
try
{
URL url = new URL(restUrl);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod(httpRequestMethod);
conn.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
conn.setRequestProperty("Content-Type", "application/json");
if (requestHeaders != null)
{
for (Map.Entry<String, String> entry : requestHeaders.entrySet())
{
conn.setRequestProperty(entry.getKey(), entry.getValue());
}
}
conn.setDoInput(true);
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
os.write(urlParameters.getBytes());
os.flush();
os.close();
if (conn.getResponseCode() != 200) {//do something}
br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
while ((output = br.readLine()) != null)
responseStrBuilder.append(output);
Approach 1:
I have below string(JSON String) as my Restful service response , how can I convert it to Java object. Since same(Itm) object is repeated multiple times if I use org.codehaus.jettison.json.JSONObject myObject = new org.codehaus.jettison.json.JSONObject(responseStrBuilder.toString());
It only reads first Itm Object and does not bring list of all item object.
JSON String output from service :
{"Response":{"RID":"04'34'",
"Itm":{"id":{"ab":"1","cd":"12"},"qw":"JK","name":"abcd "},
"Itm":{"id":{"ab":"2","cd":"34},"qw":"JK","name":"asdf "},
"Itm":{"id":{"ab":"3","cd":"12"},"qw":"JK","name":"fghj "}
}}
Approach 2:
I also tried below snippet with correct Java object with setters and getters
ObjectMapper objectMapper = new ObjectMapper();
mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
MyJavaReponseObject javaObj = mapper.readValue(json, MyJavaReponseObject.class);
This approach also reads only one object of Itm and not all the object as its not coming in array format in JSON string. Is there any better way of getting all the object(Itm) mapped to single List of Object in java pojo ?
You can use the List class in your response object, if you should parse that json string itself.
I have a ReponseJSON class with json objects, one Response and three Itms
static class ReponseJSON {
private Response Response;
#JsonProperty("Response")
public Response getResponse() {
return Response;
}
public void setResponse(Response Response) {
this.Response = Response;
}
static class Response {
private String rid;
private Itm Itm;
private List<Itm> listItm = new ArrayList<Itm>();
public Itm getItm() {
return Itm;
}
#JsonProperty("Itm")
public void setItm(Itm Itm) {
this.Itm = Itm;
listItm.add(Itm);
}
public String getRID() {
return rid;
}
public List<Itm> getItms() {
return listItm;
}
#JsonProperty("RID")
public void setRID(String rid) {
this.rid = rid;
}
static class Itm {
private Id id;
private String qw, name;
public String getQw() {
return qw;
}
public void setQw(String qw) {
this.qw = qw;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Id getId() {
return id;
}
public void setId(Id id) {
this.id = id;
}
static class Id {
private String ab, cd;
public String getCd() {
return cd;
}
public void setCd(String cd) {
this.cd = cd;
}
public String getAb() {
return ab;
}
public void setAb(String ab) {
this.ab = ab;
}
}
}
}
}
In a Response class, I have a list class and save a Itm object whenever object mapper call this class.
static class Response {
... skip ..
private List<Itm> listItm = new ArrayList<Itm>();
... skip ..
#JsonProperty("Itm")
public void setItm(Itm Itm) {
this.Itm = Itm;
listItm.add(Itm);
}
}
Check the full source code as follows.
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
public class JacksonParserTest {
static class ReponseJSON {
private Response Response;
#JsonProperty("Response")
public Response getResponse() {
return Response;
}
public void setResponse(Response Response) {
this.Response = Response;
}
static class Response {
private String rid;
private Itm Itm;
private List<Itm> listItm = new ArrayList<Itm>();
public Itm getItm() {
return Itm;
}
#JsonProperty("Itm")
public void setItm(Itm Itm) {
this.Itm = Itm;
listItm.add(Itm);
}
public String getRID() {
return rid;
}
public List<Itm> getItms() {
return listItm;
}
#JsonProperty("RID")
public void setRID(String rid) {
this.rid = rid;
}
static class Itm {
private Id id;
private String qw, name;
public String getQw() {
return qw;
}
public void setQw(String qw) {
this.qw = qw;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Id getId() {
return id;
}
public void setId(Id id) {
this.id = id;
}
static class Id {
private String ab, cd;
public String getCd() {
return cd;
}
public void setCd(String cd) {
this.cd = cd;
}
public String getAb() {
return ab;
}
public void setAb(String ab) {
this.ab = ab;
}
}
}
}
}
public static void main(String[] args) {
String responseJson =
"{\"Response\":{\"RID\":\"04'34'\","
+ "\"Itm\":{\"id\":{\"ab\":\"1\",\"cd\":\"12\"},\"qw\":\"JK\",\"name\":\"abcd\"}"
+ ",\"Itm\":{\"id\":{\"ab\":\"2\",\"cd\":\"34\"},\"qw\":\"JK\",\"name\":\"asdf\"}"
+ ",\"Itm\":{\"id\":{\"ab\":\"3\",\"cd\":\"12\"},\"qw\":\"JK\",\"name\":\"fghj\"}"
+ "}} ";
ObjectMapper mapper = new ObjectMapper();
ReponseJSON responseObj = null;
try {
responseObj = mapper.readValue(responseJson, ReponseJSON.class);
ReponseJSON.Response response = responseObj.getResponse();
for(int i = 0; i < response.getItms().size(); i++)
{
ReponseJSON.Response.Itm item = response.getItms().get(i);
System.out.println(item.getId().getAb());
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
The version of my jackson mapper is 2.9.1.
You check the main method of the source, because the JSON string you prepared is invalid as coddemonkey mentioned.
Have a good day.
Make your json response looks something similar to this
{"Response":{"RID":"04'34'",
"Itms":[{"id":{"ab":"1","cd":"12"},"qw":"JK","name":"abcd "},
{"id":{"ab":"2","cd":"34"},"qw":"JK","name":"asdf "},
{"id":{"ab":"3","cd":"12"},"qw":"JK","name":"fghj "}]
}}
then, use org.json jar to parse the string to jsonObject
JSONObject jsonObject=new JSONObject(responseString);
This is one type of solution, if you can't change the response as mentioned above then you have to manually parse the string(using java bean) there is no other option available.
I'm using Android Studio and I want to make a listview, which contains values that are received by JSON.
protected Void doInBackground(Void... voids) {
HttpHandler Handler = new HttpHandler();
String JSONString = Handler.makeServiceCall(JSONUrl);
Log.e(TAG, "Response:" + JSONString);
if(JSONString != null){
try {
JSONObject CountriesJSONObject = new JSONObject(JSONString);
JSONArray Countries = CountriesJSONObject.getJSONArray("countries");
for (int i = 1; i < Countries.length(); i++) {
JSONObject Country = Countries.getJSONObject(i);
//Details
String CountryID = Country.getString("id");
String CountryName = Country.getString("name");
String CountryImage = Country.getString("image");
//Hashmap
HashMap<String, String> TempCountry = new HashMap<>();
//Details to Hashmap
TempCountry.put("id", CountryID);
TempCountry.put("name", CountryName);
TempCountry.put("image", CountryImage);
//Hashmap to Countrylist
CountryList.add(TempCountry);
}
} catch (final JSONException e){
Log.e(TAG,e.getMessage());
ProgressDialog.setMessage("Error loading Data!");
}
}
return null;
}
This is the code for getting the JSON values, and i'm receiving an error
"No value for id"
What am I doing wrong?
You still have the "country" key to unwrap. Try like this:
for (int i = 1; i < Countries.length(); i++) {
JSONObject Country = Countries.getJSONObject(i).getJSONObject("country");
//Details
String CountryID = Country.getString("id");
String CountryName = Country.getString("name");
String CountryImage = Country.getString("image");
//Hashmap
HashMap<String, String> TempCountry = new HashMap<>();
//Details to Hashmap
TempCountry.put("id", CountryID);
TempCountry.put("name", CountryName);
TempCountry.put("image", CountryImage);
//Hashmap to Countrylist
CountryList.add(TempCountry);
}
First step is to create a new Java class model for the JSON - you can just copy and paste this.
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
public class Countries {
public class CountriesList implements Serializable {
private Country[] countries;
public Country[] getCountries() {
return countries;
}
public void setCountries(Country[] countries) {
this.countries = countries;
}
public ArrayList<Country> getCountriesAsList() {
if(countries == null || countries.length == 0) {
return new ArrayList<>();
} else {
return (ArrayList<Country>) Arrays.asList(countries);
}
}
}
public class Country implements Serializable {
private String id;
private String name;
private String image;
public Country() {
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
}
}
Now, it's simply converting the JSON into Java object like this. You can use that ArrayList for adapter or however you like.
protected Void doInBackground(Void... voids) {
HttpHandler Handler = new HttpHandler();
String jsonString = Handler.makeServiceCall(JSONUrl);
Countries.CountriesList countries = new Gson().fromJson(jsonString, Countries.CountriesList.class);
// this is the full list of all your countries form json
ArrayList<Countries.Country> countryList = countries.getCountriesAsList();
}
Note: you will need the Gson library to use the solution I showed above. I use that to convert JSON into Java object.
compile 'com.google.code.gson:gson:2.8.0'
I'm doing a Movie Project, I want to use parsing JSON to listview, I'm using loopj library, I already implement the code, but it does not work, the listview is still empty, I don't know where the error this is my code, I will show the item class first,
public class MovieItem {
private int id;
private String title;
private String description;
private String rate;
public MovieItem(JSONObject object){
try {
String title = object.getJSONArray("results").getJSONObject(0).getString("title");
String description = object.getJSONArray("results").getJSONObject(0).getString("overview");
double movieRatet = object.getJSONArray("results").getJSONObject(0).getDouble("vote_average");
String movieRate = new DecimalFormat("#.#").format(movieRatet);
this.title = title;
this.description = description;
this.rate = movieRate;
}
catch (Exception e){
e.printStackTrace();
}
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getRate() {
return rate;
}
public void setRate(String rate) {
this.rate = rate;
}
}
next, the loader is
public ArrayList<MovieItem> loadInBackground() {
Log.d("LOAD BG","1");
SyncHttpClient client = new SyncHttpClient();
final ArrayList<MovieItem> movieItemses = new ArrayList<>();
final String url = "https://api.themoviedb.org/3/search/movie?api_key="+API_KEY+"&language=en-US&query=annabelle";
client.get(url, new AsyncHttpResponseHandler() {
#Override
public void onStart() {
super.onStart();
setUseSynchronousMode(true);
}
#Override
public void onSuccess(int statusCode, Header[] headers,
byte[] responseBody) {
try {
String result = new String(responseBody);
JSONObject responseObject = new JSONObject(result);
JSONArray list = responseObject.getJSONArray("list");
for (int i = 0 ; i < list.length() ; i++){
JSONObject movie = list.getJSONObject(i);
MovieItem movieItems = new MovieItem(movie);
movieItemses.add(movieItems);
}
Log.d("REQUEST SUCCESS","1");
}catch (Exception e){
e.printStackTrace();
Log.d("REQUEST FAILED","1");
}
}
#Override
public void onFailure(int statusCode, Header[] headers,
byte[] responseBody, Throwable error) {
}
});
for (int i = 0 ; i< movieItemses.size() ; i++){
Log.d("Title",movieItemses.get(i).getTitle());
}
Log.d("BEFORE RETURN","1");
return movieItemses;
}
protected void onReleaseResources(ArrayList<MovieItem> data) {
//nothing to do.
}
pls someone help me, I already fix this problem, but nothing different
FYI I'm using API from themoviedb
I have this json string to parse {"uid":8,"totalPoints":"7740"}
I have written the below class for this.
public class Points extends WebRequest implements IWebRequest {
private static final String CLASS_TAG = Points.class.getSimpleName();
private WebAPIResponse mWebAPIResponse;
private int mUserId;
/**
* Initialize object
* #param urlEndPoint
* #param uiDelegate
* #param appContext
* #param webServiceRequestCallback
*/
public Points(String urlEndPoint, IUIDelegate uiDelegate,
WeakReference<Context> appContext,
IWebServiceRequestCallback webServiceRequestCallback) {
super(urlEndPoint, uiDelegate, appContext, webServiceRequestCallback);
}
#Override
public String parseResponse(String responseString) {
if (MBUtil.isEmpty(responseString)) {
return "";
}
String errMsg = "";
try {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
objectMapper.configure(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT, true);
if (!objectMapper.canDeserialize(objectMapper.constructType(WebAPIResponse.class))) {
return getAppContext().getString(R.string.msg_error_in_reading_format);
}
WebAPIResponse webAPIResponse = objectMapper.readValue(responseString, WebAPIResponse.class);
this.mWebAPIResponse = webAPIResponse;
Errors errors = webAPIResponse.getErrors();
if (errors != null) {
errMsg = errors.getMsg();
}
} catch (Exception e) {
Log.e(CLASS_TAG, e.getMessage());
errMsg = e.getMessage();
}
return errMsg;
}
#Override
public JSONObject buildRequestBody() {
JSONObject jsonObject = new JSONObject();
Context context = getAppContext();
if(context == null) {
return jsonObject;
}
try {
// Authentication body parameters
JSONObject authenticationJsonObject = new JSONObject();
authenticationJsonObject.put(context.getString(R.string.key_points_uid), mUserId);
return authenticationJsonObject;
} catch (Exception e) {
Log.e(CLASS_TAG, e.getMessage());
}
return jsonObject;
}
public int getUserId() {
return mUserId;
}
public void setUserId(int mUserId) {
this.mUserId = mUserId;
}
public WebAPIResponse getWebAPIResponse() {
return mWebAPIResponse;
}
public void setWebAPIResponse(WebAPIResponse mWebAPIResponse) {
this.mWebAPIResponse = mWebAPIResponse;
}
public static class WebAPIResponse {
private Data pointsData;
private Errors errors;
public Data getPointsData() {
return pointsData;
}
public void setPointsData(Data pointsData) {
this.pointsData = pointsData;
}
public Errors getErrors() {
return errors;
}
public void setErrors(Errors errors) {
this.errors = errors;
}
}
public static class Data {
#JsonProperty("uid")
private int uid;
#JsonProperty("totalPoints")
private int totalPoints;
public int getUid() {
return uid;
}
public void setUid(int uid) {
this.uid = uid;
}
public int getTotalPoints() {
return totalPoints;
}
public void setTotalPoints(int totalPoints) {
this.totalPoints = totalPoints;
}
}
}
I getting proper response in parseResponse() method which is,
responseString = {"uid":8,"totalPoints":"7740"}
But in the same pasreResponse() method once it reached to this line
if (!objectMapper.canDeserialize(objectMapper.constructType(WebAPIResponse.class))) {
return getAppContext().getString(R.string.msg_error_in_reading_format);
}
WebAPIResponse webAPIResponse = objectMapper.readValue(responseString, WebAPIResponse.class);
Not responding any thing and unable to parse the string. Please anyone check whether my parsing class is correct or not and why it is not parsing.
With your responseString = {"uid":8,"totalPoints":"7740"} you just can deserialize it by Data object only.
Data data = objectMapper.readValue(responseString, Data.class);
If you want to deserialize your JSON String to WebAPIResponse object, your responseString must be:
{"pointsData":{"uid":8,"totalPoints":"7740"}, "errors": ...}
I am parsing the JSON array successfully. But I have a String which has numbers. So I want to sort all the data according to the numbers. I had been checked so many examples but I couldn't implement them in my code.So please help me.
Here is my code. here the "count" is the, string threw which I want to sort the data.
a.java
#Override
protected Void doInBackground(Void... params) {
ServiceHandler serviceHandler = new ServiceHandler();
String jsonStr = serviceHandler.makeServiceCall(
JSONUrl.categoriesUrl, ServiceHandler.GET);
Log.d("Response Categories:", ">" + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
categoriesJSONArray = jsonObj
.getJSONArray(JSONUrl.TAG_DATA);
for (int i = 0; i < categoriesJSONArray.length(); i++) {
JSONObject c = categoriesJSONArray.getJSONObject(i);
GridViewItem gridCategoriesItem = new GridViewItem();
gridCategoriesItem.setSlug(c
.getString(JSONUrl.TAG_CATEGORIES_SLUG));
gridCategoriesItem.setImage(c
.getString(JSONUrl.TAG_CATEGORIES_IMAGE));
gridCategoriesItem.setCount(c
.getString(JSONUrl.TAG_CATEGORIES_COUNT));
mGridArrayCategories.add(gridCategoriesItem);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.d("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
GridViewItem.java
public class GridViewItem {
String image;
String slug;
String count;
String name;
public GridViewItem() {
super();
}
public GridViewItem(String image, String slug, String count,
String name) {
super();
this.image = image;
this.slug = slug;
this.count = count;
this.name = name;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public String getSlug() {
return slug;
}
public void setSlug(String slug) {
this.slug = slug;
}
public String getCount() {
return count;
}
public void setCount(String count) {
this.count = count;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Instead of using bubble sort which is o(n2).
You can use the native sort from the Collection class
example:
Collections.sort(mGridArrayCategories, new Comparator<GridViewItem>() {
public int compare(GridViewItem s, GridViewItem s2) {
return Integer.parseInt(s2.getCount()) - Integer.parseInt(s.getCount()); //this will sort your arrayList in decending order
}
});
You need to parse your string to int so it will be sorted according to the count
You can use Collection.sort().
for sorting any kind of ArrayLsit Object.
Collections.sort(listOfStringArrays,new Comparator<String[]>() {
public int compare(String[] strings, String[] otherStrings) {
return strings[1].compareTo(otherStrings[1]);
}
});