how to make retrofit POJO class for this Json - java

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());
}
}

Related

How do I POST a JSON array and get a JSON object in response using preferably android Volley?

The API I need to post to needs a JSONArray but is responding with a JSONObject. Unfortunately from what I can tell the Android Volley library has no method for this.
Is there a way to write a custom request and how would this be done to do what I explained above?
If it can not be done with Volley, how would you suggest I do it?
The method would look like this I believe:
//The array:
JSONArray itemArray = new JSONArray();
try {
for (MenuItem menuItem : listOfItems) {
JSONObject item = new JSONObject();
Log.d(LOG_TAG, "Item ID--> " + menuItem.getId());
Log.d(LOG_TAG, "Item Quantity--> " + menuItem.getNumOrdered());
Log.d(LOG_TAG, "Item Price Lvl--> " +
menuItem.getPrice_levels().get(0).getId().toString());
Log.d(LOG_TAG, "Item Comments--> " +
menuItem.getSpecialInstructions());
item.put("menu_item", menuItem.getId());
item.put("quantity", menuItem.getNumOrdered());
item.put("price_level",
menuItem.getPrice_levels().get(0).getId().toString());
item.put("comment", menuItem.getSpecialInstructions());
JSONArray discounts = new JSONArray();
JSONObject discount = new JSONObject();
discount.put("discount", null);
item.put("discounts", discounts);
JSONArray modifiers = new JSONArray();
JSONObject modifier = new JSONObject();
modifier.put("modifier",
menuItem.getModifierGroups().get(0).getId());
item.put("modifiers", modifiers);
itemArray.put(item);
}
//The volley request
JsonArrayRequest jsArrayRequest = new JsonArrayRequest(Request.Method.POST,
url, itemArray, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
finalized();
} catch (Exception e) {
Log.v("volley ex", e.toString());
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.v("volley error", error.toString());
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<>();
headers.put("Api-Key", "api key");
headers.put("Content-Type", "application/json");
return headers;
}
};
requestQueue.add(jsArrayRequest);
}
//The menuitem class
package com.garcon.garcon;
import java.io.Serializable;
import java.util.ArrayList;
public class MenuItem implements Serializable {
public String id;
public String name;
public Integer price;
protected ArrayList<PriceLevel> price_levels;
protected Boolean in_stock;
protected int modifier_groups_count;
protected ArrayList<ModifierGroup> mGroups;
//not defined in API but will give Category's ID to MenuItem
protected String categoryID;
//user defined variable
public int numOrdered = 0;
private String specialInstructions = "";
//http://stackoverflow.com/questions/18814076/how-to-make-intellij-show-
//eclipse-like-api-documentation-on-mouse-hover
/**
* Complete constructor for MenuItem.
*
* #param id The menu item’s id as stored in the POS. Sometimes a compound
value derived from other data
* #param name The name of the Menu Item as stored in the POS
* #param price The price, in cents
* #param price_levels Array of Hashes (id String Price Level Identifier,
price Integer The price of the menu item at this price level, in cents)
* #param in_stock Whether or not the item is currently available for order.
* #param mGroups Modifier Groups associated with the Menu Item.
* #param modifier_groups_count The number of Modifier Groups associated
with the Menu Item.
* #param categoryID parent category's id NOT name
*/
public MenuItem(String id, String name, Integer price, ArrayList<PriceLevel>
price_levels,
Boolean in_stock, ArrayList<ModifierGroup> mGroups, Integer
modifier_groups_count, String categoryID){
this.id = id;
this.name = name;
this.price = price;
this.price_levels = price_levels;
this.in_stock = in_stock;
this.mGroups = mGroups;
this.modifier_groups_count = modifier_groups_count;
this.categoryID = categoryID;
}
public ArrayList<PriceLevel> getPrice_levels() {
return price_levels;
}
public void setPrice_levels(ArrayList<PriceLevel> price_levels) {
this.price_levels = price_levels;
}
public String getId() {
return id;
}
public String getName(){
return name;
}
String getCategoryID() {
return categoryID;
}
public Integer getPrice(){
return this.price;
}
ArrayList<ModifierGroup> getModifierGroups(){ return this.mGroups;}
int getNumOrdered(){return this.numOrdered;}
void setNumOrdered(int amount){
numOrdered = amount;
}
String getSpecialInstructions(){return this.specialInstructions;}
void setSpecialInstructions(String instructions){
specialInstructions = instructions;
}
static class ModifierGroup implements Serializable{
private String id, name;
private Integer minimum, maximum;
private boolean required;
private ArrayList<ItemModifier> modifier_list;
public ModifierGroup(String id, String name, int minimum, int maximum,
boolean required, ArrayList<ItemModifier> modifier_list){
this.id = id;
this.name = name;
this.minimum = minimum;
this.maximum = maximum;
this.required = required;
this.modifier_list = modifier_list;
}
public ModifierGroup(){}
String getId(){return id;}
String getName(){return name;}
Integer getMinimum(){return minimum;}
Integer getMaximum(){return maximum;}
boolean isRequired(){return required;}
ArrayList<ItemModifier> getModifierList(){ return
this.modifier_list;}
static class ItemModifier implements Serializable{
private String id, name;
private Integer price_per_unit;
private ArrayList<PriceLevel> priceLevelsList;
//user defined variable
private boolean added = false;
public ItemModifier(String id, String name, Integer
price_per_unit, ArrayList<PriceLevel> priceLevelsList){
this.id = id;
this.name = name;
this.price_per_unit = price_per_unit;
this.priceLevelsList = priceLevelsList;
}
String getId(){return id;}
String getName(){return name;}
Integer getPricePerUnit(){return price_per_unit;}
ArrayList<PriceLevel> getPriceLevelsList(){return
priceLevelsList;}
boolean isAdded(){ return added;}
void setAdded(boolean b){added = b;}
}
static class ItemModifierGrouped extends ItemModifier implements
Serializable{
private int group_id;
public ItemModifierGrouped(String id, String name, Integer
price_per_unit, ArrayList<PriceLevel> priceLevelsList, int
group_id){
super(id,name,price_per_unit,priceLevelsList);
this.group_id = group_id;
}
}
}
public static class PriceLevel implements Serializable{
public String id;
public Integer price;
public PriceLevel(){}
public PriceLevel(String id, Integer price){
this.id = id;
this.price = price;
}
public String getId(){return id;}
public Integer getPrice(){return price;}
}
}
try this
final String httpUrl = url;
Log.i(TAG,httpUrl.toString());
try{
JSONArray parametersForPhp = new JSONArray();
JSONObject jsonObject = new JSONObject();
jsonObject.put(key,"0");
jsonObject.put("key","");
jsonObject.put(key,sharedPreferences.getString(PATIENT_ID,BLANK));
jsonObject.put(APP_LANGUAGE,sharedPreferences.getString(APP_LANGUAGE,BLANK));
parametersForPhp.put(jsonObject);
JsonArrayRequest arrayRequest = new JsonArrayRequest(Request.Method.POST, httpUrl, parametersForPhp,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.i(TAG,response.toString());
if (response==null){
Toast.makeText(getApplicationContext(),"Please Try Again!",Toast.LENGTH_SHORT).show();
}else {
try {
//you code
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
RequestQueueSingleton.getInstance(getApplicationContext()).addToRequestQueue(arrayRequest);
}catch (Exception e){
e.printStackTrace();
}

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 retrieve the result as JSON Arrray format in REST Response

I am trying to retrieve the data from database and return them in 'Response' as JSON array.
But now I am getting the result in browser as below, which is not the correct JSON array format. How can I receive the data as JSON Array ?
{"{\n \"id\": 14,\n \"name\": \"Test Doom Post\",\n \"email\": \"test#test1.com\...
JDK 1.7
Jersey (jaxrs-ri-2.25.1)
Gson
//Following is my Get method below:
#Path("/register")
public class JSONService {
#GET
#Path("/get")
#Produces("application/json")
#Consumes("application/json")
public Response getRegisterInJSON() {
JSONObject requestedJSON = new JSONObject();
try {
Class.forName("com.mysql.jdbc.Driver");
SoccerUtils dbConnection = new SoccerUtils();
Connection conn = dbConnection.getWeekendDBConnection();
PreparedStatement stmt = conn.prepareStatement("SELECT ID, FIRST_NAME, EMAIL FROM mycoolmap.weekendsoccer_login");
ResultSet rs = stmt.executeQuery();
while(rs.next())
{
RegisterPlayer playerObj = new RegisterPlayer();
playerObj.setId(rs.getInt("ID"));
playerObj.setName(rs.getString("FIRST_NAME"));
playerObj.setEmail(rs.getString("EMAIL"));
Gson gson = new GsonBuilder().setPrettyPrinting().create();
String json1 = gson.toJson(playerObj);
requestedJSON.put(json1, json1);
System.out.println(requestedJSON);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
}
return Response.status(Status.OK).entity(requestedJSON.toString()).build();
}
// Register Player POJO class:
#XmlRootElement
public class RegisterPlayer implements Serializable {
private int id;
private String name;
private String email;
public RegisterPlayer() {
}
public RegisterPlayer(int id, String name, String email)
{
super();
this.id =id;
this.name = name;
this.email = email;
}
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;
}
public String getEmail()
{
return email;
}
public void setEmail(String email)
{
this.email = email;
}
#Override
public String toString() {
return "RegisterPlayer[id=" + id +", name=" + name +", email="+ email +"]";
}
}
As advised by Roman in above comment, I have created a list, add the object and return the list. It worked as expected.
/Created a 'registerPlayerList' List
List<RegisterPlayer> registerPlayerList = new ArrayList<RegisterPlayer>();
// Intialiaze the RegisterPlayer class
RegisterPlayer playerObj = new RegisterPlayer();
//set all the values into the object
playerObj.setId(rs.getInt("ID"));
playerObj.setName(rs.getString("FIRST_NAME"));
playerObj.setEmail(rs.getString("EMAIL"));
......
//add the playerObj to the created registerPlayerList
registerPlayerList.add(playerObj);
// return the list
return registerPlayerList ;
The problem is that you're printing the json to string (the json1 variable), but you're adding that string to a JSONObject. When a string is added to a JSONObject, the string will be escaped - that's a String json object.
If you print json1 instead (and set that as the entity), it should work.

Converting String containing Json to gSonObject

I have a string that contains the following Json data
[{"date":"11/8/2014","auther":"nirav kalola","description":"json object parsing using gson library is easy","post_name":"json object parsing"},{"date":"12/8/2014","auther":"nirav kalola","description":"json array parsing using gson library","post_name":"json array parsing"},{"date":"17/8/2014","auther":"nirav kalola","description":"store json file in assets folder and get data when required","post_name":"json parsing from assets folder"}]
i want to convert it to gSon
i tried following code
protected void onPostExecute(String result) {
Toast.makeText(getBaseContext(), "Received!", Toast.LENGTH_LONG).show();
//etResponse.setText(result);
try {
Type listType = new TypeToken<ArrayList<BeanPost>>() {
}.getType();
ArrayList<BeanPost> beanPostArrayList = new GsonBuilder().create().fromJson(result, listType);
// Above Line gives error
// JsonDeserializer could not Deserialize the object
StringBuffer postList = new StringBuffer();
for (BeanPost post : beanPostArrayList) {
postList.append("\n title: " + post.getPost_name() +
"\n auther: " + post.getAuther() +
"\n date: " + post.getDate() +
"\n description: " + post.getDescription() + "\n\n");
}
}
catch(Exception e2)
{
String msg=e2.getLocalizedMessage();
e2.printStackTrace();
}
}
BeanPost.java Class is as follows
package com.jobwork.mujahidniaz.ws2;
/**
* Created by Mujahid Niaz on 06/09/2016.
*/
import com.google.gson.annotations.SerializedName;
public class BeanPost {
#SerializedName("post_name")
private String post_name;
#SerializedName("auther")
private String auther;
#SerializedName("date")
private String date;
#SerializedName("description")
private String description;
public BeanPost(String post_name, String auther, String date, String description) {
this.post_name = post_name;
this.auther = auther;
this.date = date;
this.description = description;
}
public String getPost_name() {
return post_name;
}
public void setPost_name(String post_name) {
this.post_name = post_name;
}
public String getAuther() {
return auther;
}
public void setAuther(String auther) {
this.auther = auther;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
I have tried a lot of search on google but could not find the Answer please help me with that.
(Untested code)
first you must create your empty public constructor from your BeanPost.java since you have custom constructor.
public BeanPost(){}
Gson gson = new Gson;
List<BeanPost> myBPost = gson.fromJson(result, List<BeanPost.class>); //i assume that result is your json string
now you're got to with your for each to get the value. Hope it helps

how to autoGenearte _id instead of mongoDB ObjectId()

How to genearate "_id" : "01A63D2B-1724-456E-B2C0-3B3729951654" instead of "_id" : ObjectId("570602c46399e320c3022c6b")
My Student.class
#Entity("student")
public class Student {
#Id
private String Id;
private long studentId;
private String studentName;
private String qualification;
public Student(){
}
public Student(long studentId, String studentName, String qualification) {
this.studentId = studentId;
this.studentName = studentName;
this.qualification = qualification;
}
public long getStudentId() {
return studentId;
}
public void setStudentId(long studentId) {
this.studentId = studentId;
}
public String getStudentName() {
return studentName;
}
public void setStudentName(String studentName) {
this.studentName = studentName;
}
public String getQualification() {
return qualification;
}
public void setQualification(String qualification) {
this.qualification = qualification;
}
}
Function to add JSON Data to MOngoDB:
public void importFromJsonToMongoDB(File file) throws FileNotFoundException{
try{
String strJson = FileUtils.readFileToString(file, StandardCharsets.UTF_8);
JSONArray jsonArr = new JSONArray(strJson);
for (int i = 0; i < jsonArr.length(); i++)
{
JSONObject jsonObj = jsonArr.getJSONObject(i);
String str = jsonObj.toString();
ObjectMapper mapper = new ObjectMapper();
Student std = mapper.readValue(str, Student.class);
sr.save(std);
}
}catch (Exception e) {
e.printStackTrace();
System.out.println("Error While parsing data");
}
* How to Auto Generate id? rather than MongoDb generating it.
I think you need to add "_id" field while inserting the document in MongoDB. since you are not specifying any "_id" field it will automatically be generated by MongoDB. You can also use getNextSequence() method of mongodb to generate the id according to your preference.
Note: StudentID and _id are two different entities in the same document.
I hope these link will be useful for you:
https://docs.mongodb.org/manual/tutorial/create-an-auto-incrementing-field/
Replace the existing NO-arg Constructor with following one in
Student.class
public Student(){
super();
id = UUID.randomUUID().toString();
}
This will generate random id instead of MongoDB ObjectId

Categories

Resources