Android fetch volley data from a string of arrays - java

AM sending a request using android volley and get a response like this
public void onResponse(JSONObject response
try {
String responsedata = response.getString("data");
Log.i("test",responsedata);
} catch (JSONException e) {
e.printStackTrace();
}
}
The above log prints
[{"id":1,"identifier":"TYam Plant","header_val":"tyamplant"},
{"id":2,"identifier":"Touron Plant","header_val":"toroun"}
]
Now i would like to loop through these and extract an array of individual properties that is
id, identifier, header_val
How do i go about this. Am still new to java

You response is JSONArray not JSONObject check it
You need to use JSONArray request instead of JSONObject request of volley
Try this to parse your json
try {
JSONArray jsonArray= new JSONArray(responsedata);
for (int i=0;i<jsonArray.length();i++){
JSONObject object=jsonArray.getJSONObject(i);
String id=object.getString("id");
String identifier=object.getString("identifier");
String header_val=object.getString("header_val");
}
} catch (JSONException e) {
e.printStackTrace();
}
Better to Parse your JSON Using google-gson-library
Gson is a Java library that can be used to convert Java Objects into their JSON representation. It can also be used to convert a JSON string to an equivalent Java object. Gson can work with arbitrary Java objects including pre-existing objects that you do not have source-code of
EXAMPLE : How to Parse JSON Array with Gson

You create a Custom Object with 3 field: id, identifier,header_val
public class YourObject {
private String id;
private String identifier;
private String header_val;
public YourObject(String id, String identifier, String header_val) {
this.id = id;
this.identifier = identifier;
this.header_val = header_val;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getIdentifier() {
return identifier;
}
public void setIdentifier(String identifier) {
this.identifier = identifier;
}
public String getHeader_val() {
return header_val;
}
public void setHeader_val(String header_val) {
this.header_val = header_val;
}
}
Loop and add into list: List<YourObject> yourList = new ArrayList<>();
try {
JSONArray jsonArray= new JSONArray(responseString);
for (int i=0; i<jsonArray.length();i++){
JSONObject object=jsonArray.getJSONObject(i);
String id=object.getString("id");
String identifier=object.getString("identifier");
String header_val=object.getString("header_val");
yourList.add(new YourObject(id, identifier, header_val);
}
} catch (JSONException e) {
e.printStackTrace();
}

Related

Android Studio - Issue loading JSON

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'

how to make retrofit POJO class for this Json

here is the json form that i try to make pojo class for it
[{"ID":"1",
"SectionName":""
,"Title":"testosss"}
,{"ID":"2"
,"SectionName":"",
"Title":"test"}]
i have one array with list of object what should i do to make pojo class in this case ?
Generate pojo class using jsonschema2pojo
import java.util.HashMap;
import java.util.Map;
public class Example {
private String iD;
private String sectionName;
private String title;
public Example(){
}
public Example(String id,String sectionName,String title){
this.iD = id;
this.sectionName = sectionName;
this.title = title;
}
public String getID() {
return iD;
}
public void setID(String iD) {
this.iD = iD;
}
public String getSectionName() {
return sectionName;
}
public void setSectionName(String sectionName) {
this.sectionName = sectionName;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}
whenever you have multiple jsonArray value in your json data, we need to store all data in ArrayList. here i have make some code for you i hope might be helpful you.
Your json data
String jsonDemo = "[{\"ID\":\"1\",\n" +
"\"SectionName\":\"\"\n" +
",\"Title\":\"testosss\"}\n" +
",{\"ID\":\"2\"\n" +
",\"SectionName\":\"\",\n" +
"\"Title\":\"test\"}]";
for get josn data and store in ArrayList with Example pojo class
create ArrayList class with pojo model class
ArrayList<Example> arrayList = new ArrayList<>();
json parsing and store each data in arraylist
try {
JSONArray jsonArray = new JSONArray(jsonDemo);
for(int i=0;i<jsonArray.length();i++){
JSONObject jsonObject = jsonArray.getJSONObject(i);
String ID = jsonObject.getString("ID");
String sectionName = jsonObject.getString("SectionName");
String title = jsonObject.getString("Title");
arrayList.add(new Example(ID,sectionName,title));
}
} catch (JSONException e) {
e.printStackTrace();
}
Retrieve all json data
if(arrayList.size()>0){
for(int i=0;i<arrayList.size();i++){
Example example = arrayList.get(i);
Log.d("Example","ID : " + example.getID());
Log.d("Example","getSectionName : " + example.getSectionName());
Log.d("Example","getTitle : " + example.getTitle());
}
}

Create "tagged" Json Object, instead of just properties

I'm having some problems when i try to deserialize my object into a json string.
I'm getting the following object:
{
"idUser": 1,
"name": "2",
...
}
But I want to achieve this object:
{
"user": {
"idUser": 1,
"name": "2",
...
}
}
I'm serializing my object using this code:
public static String deserializeUser(User user){
ObjectMapper objectMapper = new ObjectMapper();
String json = "";
try {
json = objectMapper.writeValueAsString(user);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return json;
}
I'm using the api com.fasterxml.jackson
And here goes my User class:
public class User {
public long idUser;
public String name;
public String email;
public String phoneNumber;
#JsonProperty("cpf")
public String CPF;
public String password;
public boolean active;
private String facebookPictureUrl;
private String cameraTakenPhotoBase64;
private String facebookUserId;
... (constructor and getters/setters)
}
That is because you're serializing an instance of User. The intended JSON matches a map with a user property. So you could achieve it with:
Map<String, User> userMap = new HashMap<String, User>();
userMap.put("user", user);
String json = "";
try {
json = objectMapper.writeValueAsString(userMap);
} catch (JsonProcessingException e) {
e.printStackTrace();
}

Can not deserialize instance of test.MyPojo out of START_ARRAY token

I am not able to convert my JSON to POJO objects.
My JSON output is:
[ {
"id" : 1,
"name" : "latha"
}, {
"id" : 2,
"name" : "kala"
}]
My POJO is:
public class NSCLockData {
private int id;
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
My class is:
public void insert(org.springframework.messaging.Message<?> msg) throws JsonGenerationException, JsonMappingException, IOException{
ObjectMapper mapper = new ObjectMapper();
try {
MyPojo data=mapper.readValue(msg.getPayload().toString(), MyPojo.class);
this.sessionFactory.getCurrentSession().saveOrUpdate(data);
} catch (JsonGenerationException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Create your new POJO so that it should be array of NSLoackData
public class ArrayofNS implements Serialaizable(){
// create serialisation
private List<NSLoackData> arrayof;
// getter and setteers
}
In Your main code where you need to convert the incoming json to your POJO class write something like below
consider u have the above JSON (Array ) in a JSONObject called result;
JSONArray js = new JSOANArray();
convert your above json into JSONArray with the above line of code
js = result;
iterate through the loop and get the value
List<NSLockData> lk = new ArrayList<NSLockData>();
NSLockData data;
for(I=0;i<=js.length();I++){
data = new NSLockDate();
data = new ObjectMapper.readValue(js.get(i).toString(),NSLOckData.class);
lk.add(data);
}

Convert class into a JSONObject

I have several classes like this. I want to convert the classes into JSONObject format.
import java.io.Serializable;
import com.google.gson.annotations.SerializedName;
public class User implements Serializable {
private static final long serialVersionUID = 1L;
#SerializedName("id")
private Integer mId;
#SerializedName("name")
private String mName = "";
#SerializedName("email")
private String mEmail;
public Integer getId() {
return mId;
}
public void setId(Integer id) {
mId = id;
}
public String getName() {
return mName;
}
public void setName(String name) {
mName = name;
}
public String getEmail() {
return mEmail;
}
public void setEmail(String email) {
mEmail = email;
}
}
I know that I can convert these classes to JSONObject format as follows:
User user = new User();
JSONObject jsonObj = new JSONObject();
try {
jsonObj.put("id", user.getId());
jsonObj.put("name", user.getName());
jsonObj.put("email", user.getEmail());
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
The problem is that I need to do this for a lot of different classes that are much longer than this across a lot of files. Can I use GSON to fill the JSONObject from myClass so that I don't need to edit every time the class structure changes?
The following returns a JSON string but I need it as an Object as when I send it to the system that sends the requests via a REST API it sends with unwanted quotation marks.
User user = new User();
Gson gson = new Gson();
Object request = gson.toJson(user);
When I use this in another JSON builder that asks for an Object I get
{"request":"{"id":"100","name":"Test Name","email":"test#example.com"}"}
When I want
{"request":{"id":"100","name":"Test Name","email":"test#example.com"}}
I found that the following works with GSON:
User = new User();
Gson gson = new Gson();
String jsonString = gson.toJson(user);
try {
JSONObject request = new JSONObject(jsonString);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
This is not type safe, however.
Here is a crude example you can use to use Reflection to build the JSONObject..
Warning it's not pretty and does not contain really type-safety.
public static JSONObject quickParse(Object obj) throws IllegalArgumentException, IllegalAccessException, JSONException{
JSONObject object = new JSONObject();
Class<?> objClass = obj.getClass();
Field[] fields = objClass.getDeclaredFields();
for(Field field : fields) {
field.setAccessible(true);
Annotation[] annotations = field.getDeclaredAnnotations();
for(Annotation annotation : annotations){
if(annotation instanceof SerializedName){
SerializedName myAnnotation = (SerializedName) annotation;
String name = myAnnotation.value();
Object value = field.get(obj);
if(value == null)
value = new String("");
object.put(name, value);
}
}
}
return object;
}
Here is an example usage:
User user = new User();
JSONObject obj = quickParse(user);
System.out.println(obj.toString(3));
Output
{
"id": "",
"name": "",
"email": ""
}
Try with this code:
// Returns the JSON in a String
public String getJSON()
{
Gson gson = new Gson();
return gson.toJson(this);
}
// Builds the Model Object from the JSON String
MyModel model =new MyModel();
JSONObject j = new JSONObject(model.getJSON());

Categories

Resources