I want to post this kind of request in retrofit2 so if someone have idea about it then it would be great help of mine.
reqObject={"task":"singleUser","taskData":{"userID":"1"}}
Yes, good Question It is some what not understandable for Beginner.
So I combining some Answers for you.
first step
make your Json -> model class (or POJO class)
From GsonFormattor plugin
This plug-in convert your Json to Model class
Pojo genrator
Go to this link , copy and paste Your Json and simply make your model class.
OK , we completed our first step
Second Step
Set all value to your Model class what You want from getter() setter().
Retrofit having #Body annotation that use in your case
#POST("/jayson")
FooResponse postJson(#Body MyGsonModelClass body);
Where MyGsonModelClass is class we made from first step.
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'm using Moshi 1.8.0 on Android, and I'm following the instructions on the Moshi documentation create custom fields: https://github.com/square/moshi#custom-field-names-with-json
This means that my request data class is like this:
data class GetStuff(
#Json(name = "RequestContext") val context: RequestContext,
)
but the issue is that the actual HTTP request gets sent like this:
{"context": "blah... }
What I'm expecting to happen is for my request to be like this instead:
{"RequestContext": "blah... }
This seems to work fine for the response, but I can't figure out how to make it work for the request.
Thank you!
Is this not how the #Json(name = "") annotation works for request?
Ugh, I'm an idiot.
I'll answer this for whoever needs this in the future (likely me again).
In order to convert Json to an data class, you have to change your API call to be have this annotation:
#MoshiDeserialization
I knew that, and that's the magic annotation that makes deserialization work.
However, I didn't know I also needed a second magic annotation for the serialization part to work as well:
#MoshiSerialization
Now it works.
The problem is next.
In response I have JSON like
{
object: {
// a lot of different fields
}
}
I use Retrofit with gson parser. What I really need is just this object. I don't want to create class for response with the only one field. All responses server send in a such manner. As far I understand somewhere I need place simple code for fetching that one object and then use default parser for it.
Probably sorry for stupid question. I used Volley and there was quite a different approach.
Instead of creating a special class to handle this (and another special class for every other server response), just use Map<String, YourRealObjectType>. Then use this method to extract the YourRealObjectType instance for each response:
public static <T> T getFirstValue(Map<String, T> map) {
return map.values().iterator().next();
}
you can convert class into JsonObject class. then cal iterate all the elements in it one by one
#Get
ObservablegetData();
Note : use JsonObject not JSONObject
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());