How do I post a json array with retrofit2?
For example,
http://www.test.com/post/listparam=[{id=1,name="A"},{id=2,name="B"}]
If you want to pass any json,pass pojo class or bean class
For Example if your json is like this
{
"main":{"id":"1","name":"A"}
}
Then paste your json string in jsonshematopojo.org,
In source type click JSON radio button,In Annotation style select Gson and also click include constructers(You can download your generated bean classes by clicking Zip button).Then instead of passing json pass like this
new Example(new Main(id,name));
Instead of declaring String parameter in interface declare Example(Your main bean class name
Related
How to Get object from verticals from json android.
I have got the vertical object.
JSONObject obj = new JSONObject(loadJSONFromAsset());
Log.d(String.valueOf(obj),"obj");
want other 4 which are
health care
environmental care
agricultural product
consumer product
You can get JSON Objects from main object as follow:
1- Create Model classes for your JSON string. You can either use jsonschema2pojo or Android Plugins to create models classes for you.
2- Then follow this code
Response response = new Gson().fromJson(loadJSONFromAsset(), Response.class);
List<CartridgesItemItem> cartridges = response.getVerticals().getHealthCare().getCartridges();
List<PackingRollsItemItem> packingRolls = response.getVerticals().getHealthCare().getPackingRolls();
List<SterilizersItemItem> sterilizers = response.getVerticals().getHealthCare().getSterilizers();
where Response is my main model class created.
====================================================================
====================================================================
If you want to install plugin in Android Studio for converting JSON to model classes follow these steps:
1- You can go to Android Studio settings -> Plugins
2- search for RoboPOJOGenerator and install it
3- Then click on any package/folder on left side of your android studio
Select package -> new -> Generate POJO from JSON
See here
4- Paste your Json string and Write name for your main class
See here
5- Use above code mention in 2nd point for getting your string as model class (Response)
Note: you might need to add this dependency in build.gradle app
//GSON
implementation 'com.google.code.gson:gson:2.8.9'
Hope this helps !!
You can easily create Model class with response:
https://www.jsonschema2pojo.org/
check this website. If you can not achieve your task then use any android studio plugin to create model classes.
The best way to do it would be to create a POJO class. The alternate solution to this would be to get Object from JSON and use it in your Model Object
JSONObject obj = new JSONObject(loadJSONFromAsset());
JSONObject healthCare = obj.optJSONObject("Health Care")
This is just another way to get json object from JSON. POJO classes should be the way it is done as mentioned in the answer by #Ali Ahmed
I need to parse only one list of objects from JSON object with Retroft.
Here's my JSON file
I need only "similar" array from it. Also I've already created POJO for elements of this array
Is there a way to make this without making POJO for the rest of the JSON file?
Just make pojo with necessary fields:
data class ServerResponse(
val recipe: RecipeResponse
)
data class RecipeResponse(
val similar: List<RecipeBrief>
)
I am working on json currently in android, but now i follow getter and setter methods to parse json. For example. if there are 5 fields in json string, so create 5 getter and setter methods in one class and accordingly parse the string.
But now in future if one more field increases in json string, then again i need to add one more getter and setter method in that class.
So my question is can we parse json without getter setter, without any class? so that if json changes in future it can be handled well without adding new getter and setter method.
Please let me know the dynamic way to handle json.
you can use these web site http://www.jsonschema2pojo.org/
for creating a class if in future any field increase just put the json in that it will automatically create a class for you .
I am new to GSON, JSON & hence asking the question:
At the android end, I have to send a booking information to the REST WS on the server. So here is the question:
I have a BookingDTO & I use GSON to serialize it. I send it the REST WS on the server. Now do I also need the same BookingDTO at the server end for GSON deserialize it? (But that would mean tight coupling right?) Do I have to use GSON or can I use normal JSON?
What should be my approach?
You can use Json and parse that content into your objects or directly deal with JsonObject and JsonArray in your methods (server side).
if you want to use objects like BookingDTO you can either re create the classes on android project or reuse those classes from your server side, (or vice versa).
by creating a JAR file that only contains those classes (ex, export model package only) where all POJO classes are located.
using a JAR file makes you maintain a consistency between server and client code, when you add/delete a field, you don't have to change 2 classes, just change in one place and re export the JAR.
now to the tight coupling issue, i don't think there is a one here.
because you are using a list of classes (and you need them in 2 or more separate locations/projects...) this is not coupling, this is reusing same code which should be a good practice.
Coupling is -for example- when Class A is a member of Class B, but it's not when you use Class A and Class B in 2 different systems/components ...
do I also need the same BookingDTO at the server end for GSON
deserialize it?
Simply put, yes, you'll have to prepare a POJO in order to receive the request. So, for that to happen, JSON deserializer will try to parse the properties off JSON request and map that to a POJO of server.
With Spring, we do stuffs like the following. This is a creating a controller of POST request type expecting to habe a param of BookingDTO type. We use Jackson library for JSON serialize and deserialize.
#RequestMapping(value = {"/update"}, method = RequestMethod.POST)
#ResponseBody
public void update(#RequestBody BookingDTO bookingDTO) throws FamsException {
// Do what you intend to do with this bookingDTO object sent from client side(Android)
}
As it stands, if your JSON property name matches with the property name and type of BookingDTO then it can map those and you'll get BookingDTO bookingDTO object with all the matched properties.
Be sure not to send JSON request with property that isn't in the BookingDTO POJO. Otherwise, server will throw a 400 BAD REQUEST error.
Note that, you can also send Map as parameter. This won't require a matching POJO at server side. You can construct a different object by getting the data out of Map the way you like.
Hope you get the idea.
I have a large json page which contains url:http://akhilmadanan.tk/Akhil/database.php.
While i am parsing this page using normal json parsing method it shows "OutOfMemoryError". For this i heard about GSON. Please any body help me get how to read the datas from below page using GSON.
any tutorial?
Here'a good tutorial:
http://www.javacodegeeks.com/2011/01/android-json-parsing-gson-tutorial.html
You can also check out their official user guide:
https://sites.google.com/site/gson/gson-user-guide
Hope this helps :-)
Instead of returning all the data, why don't you break it into chunks? That would require less memory at processing time.
Thats assuming you have access to the database level/response.
You can definitely go to links provided by others which are helpful
For brief you can add GSON library in your lib folder.
and use like this.
Gson gson=new Gson();
To get object from json
Model model=gson.fromJson(json,Model.class);
To convert to json
String json=gson.toJson(model);
I run your code and there are 3010 items of object
[
{
"cust_no":"70105615002",
"cust_name":"akhil",
"address":"kajffjkhfhhkjsd",
"area":"58695",
"ranges":"4586",
"plot":"69896",
"multifactor":"85758",
"electricity_meterno":"7895",
"water_meterno":"69358",
"gas_metrno":"78956",
"traffic_code":"4587855",
"last_meter":"58695",
"previous_reading":"25638",
"date":"589687",
"current_usage":"789654",
"current_balance":"45876",
"last_recipt":"236584"
},....
Now make a model equivalent to above name like
#SerializedName("cust_no")
private Long custNo;
#SerializedName("cust_name")
private Long custName;
..........
remember to add one list of same class type like
#SerializedName("custname")
private List<Customer> customerList;
and generate getters and setters of that Customer class;
after this
parse your data like this
CustomerModel customerModel=gson.fromJson(json,Customer.class);
you get all your data in customerModel;
To access data just use list of that class.
List<Customer> customerList=customerModel.getCustomerList();
Log.v("APP_NAME",""+customerList.size());