I'm working on fixing an issue on an Android app using Java. I have a custom ArrayList which I want to pass to a server as JSON. I just want to know is this possible? When I pass in an ArrayList of type String it passes to the server perfectly fine. Any help or links to articles on this would be extremely helpful.
I have used GSON library from Google for converting ArrayList or even collection of custom complex type to JSON.
GSON provides you capability to register custom serializer/deserializers as well. See documentation.
To start with try following code snippet to serialize an ArrayList.
ArrayList<CustomObject> arrayList = ...
Gson gson = new Gson();
String serializedJson = gson.toJson(arrayList);
Related
I am trying to parse the results of an API call which returns a unique first property.
{
"AlwaysDifferent12345": {
"fixedname1" : "ABC1",
"fixedname2" : "ABC2"
}
}
I am using retrofit2 and jackson/gson and cannot figure out how to cope with dynamic property names within the retrofit2 framework. The following works fine
data class AlwaysDifferentDTO(
#JsonProperty("AlwaysDifferent12345") val alwaysDifferentEntry: AlwaysDifferentEntry
)
I have tried
data class AlwaysDifferentDTO(
#JsonProperty
val response: Map<String, AlwaysDifferentEntry>
)
But this returns errors Can not instantiate value of type... The return value from the API is fixed i.e. map<string, object>.
I have read you can write a deserializer but it looks like I need to deserialize the whole object when all I want to do is just ignore the string associated with the response.
I have read
https://discuss.kotlinlang.org/t/set-dynamic-serializedname-annotation-for-gson-data-class/14758
and several other answers. Given unique properties names are quite common it would be nice to understand how people deal with this when using retrofit2
Thanks
Because the JSON doesn't have a 1-to-1 mapping Jackson can't map it automatically using annotations. You are going to need to make your own Deserializer.
In this tutorial you can learn how to create your own custom Deserializer for Jackson. https://www.baeldung.com/jackson-deserialization
In the tutorial you will see the first line under the deserialize function is
JsonNode node = jp.getCodec().readTree(jp);
using this line you can get the JSON node as a whole and once you have it you can call this function
JsonNode AlwaysDifferent12345Node = node.findParent("fixedname1");
Now that you have that node you can retrieve its value like shown in the rest of the tutorial. Once you have all the values you can return a new instance of the AlwaysDifferentDTO data class.
I am developing android listing images app where I got array from server side. But I have issue to read array or don't know how to get it.
Below array i got from server API call:
{"lists":["http:\/\/xyz.com\/projects\/photo\/birthday\/1.jpg","http:\/\/xyz.com\/projects\/photo\/birthday\/3.jpg","http:\/\/xyz.com\/projects\/photo\/birthday\/4.jpg"],"Status":"1"}
How to read it and display images in loop.
Thanks
If you are using gson library for parsing json respose then you could simply write a separate class
like this
public class ImageResponse{
public String Status;
public List<String> lists;
}
NOTE: when creating a class the object names of the class should match with the tag names from the server..
Then using gson
ImageResponse detail = (new Gson()).fromJson(
response.toString(), ImageResponse.class);
where response is your response from the server
now u can access the list like
List<String> images =details.lists;
Now you have all the images in the list form, you can load the images using Picasso[lets say in a listview]
Picasso.with(context).load(images[0]).into(imageView);
For using this you should add GSON library to your dependency in your app gradle
compile 'com.google.code.gson:gson:2.2.4'
There are many other method too, feel free to search and find out may be there will be more optimized code than this..
I've been searching for the past week on how to develop an android project, read some on android developers page and on other websites like here, but no text was complete.
i have this project - i'm a php developer not a java, but could understand a bit about java lately.
the thing is i want to develop an android app using my website, i did output a json type data from my website, and gonna use them on the android app, i did the async request on android and could read the data form the website but :
first question: how to parse the json data correctly and convert it to array on android, i did that through:
Iterator<String> itr = myObject.keys();
while (itr.hasNext()) {
...
i don't know if that's the correct way, when i try to convert my json object to array, it gives me type mismatch.
second and more importantly:
how can create a "Block" like facebook posts style, or twitter style blocks, you know - blocks of json data, is it a linearlayout ? what do i call it ? and how can i add it to the UI dynamically, cuz these blocks are pulled from the website json data. so they are arrays...of blocks..
i'm kinda confused still, i need a start point.
Thank you!
excellent tutorial for beginners for android development
http://thenewboston.org/list.php?cat=6
and for your first question - how to parse json data correctly,
you can try using gson to convert the json data into POJO
otherwise you'd have to do myObject.opt(key) to make sure it is there
First question: you should use a library to parse JSON, it's simpler that way. Try gson. You should create a class, which holds the parsed object, like:
public class Taxi implements Serializable {
private static final long serialVersionUID = 1L;
#SerializedName("idTaxi")
private Integer idTaxi;
#SerializedName("name")
private String name;
//getter, setters, constructor, etc
}
Then when you get the JSON object, you can parse it:
Gson gson = new Gson();
Reader reader = new InputStreamReader(SOURCE_STREAM);
Taxi[] response = gson.fromJson(reader, Taxi[].class);
Second question: i think a ListView would be good for you. You can read a full tutorial about it here
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());
I have something like the following json string:
{"values" : [
{ "group":"A"
"rating":2
},
{
"group":"B"
"language":"english"
}
]
}
As you can see, "values" is an array, with different type of objects. One type can contain a string and an integer, and the other type contains a string and another string.
How do I deal with this?
Sorry, I didn't notice originally you wrote "gson". I'm not sure you can do it, and here's not me saying it.
Do some thing like the following
List myStrings = new ArrayList();
myStrings = gson.fromJson(json,myStrings.getClass());
Iterator myIterator = myStrings.iterator();
boolean b;
while(myIterator.hasNext()){
Object o =myIterator.next();
b=o instanceof String;
System.out.println("...."+b);
}
My approach would probably be to implement a polymorphic deserialization solution.
Gson does not currently have a simple mechanism for polymorphic deserialization, other than implementing custom deserialization processing. The next release looks like it will provide a built-in solution.
Previous StackOverflow.com Questions And Answers (Some With Examples) On This Topic:
Deserialising a generic with unknown compile time type where a field indicates the type
Parse JSON with no specific structure for a field with GSON
json object serialization/deserialization using google gson
Polymorphism with gson
Specific to the original question, it looks like the "group" element would be used to distinguish between different types.
FWIW, Jackson released a built-in solution to this problem many moons ago.