How to parse json page using gson? - android

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

Related

Parsing API results on Android with Retrofit and Jackson or Gson

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.

Using Klaxon JSON for Android how can I get the following JSON in to a ListView?

I'm looking on how to use Klaxon to get my JSON into an Array for a LIstView. This is different then Java for two reasons. It is Kotlin and Klaxon.
Below is a array of zips and info for towns in a state. I'm pulling it via Fuel and I can get it into Klaxon to read parts of the objects into text fields but I want to build a list where each object has its own row. Was wondering how to get from point A klaxon into the List point B.
Not sure how to go about this.
{"towns":[{"zip":"02052","City":"Medfield","State":"MA","lat":"42.178","Long":"-71.3059"},{"zip":"02054","City":"Millis","State":"MA","lat":"42.1677","Long":"-71.3601"},{"zip":"02081","City":"Walpole","State":"MA","lat":"42.1429","Long":"-71.2571"},{"zip":"02030","City":"Dover","State":"MA","lat":"42.2341","Long":"-71.2861"},{"zip":"02056","City":"Norfolk","State":"MA","lat":"42.1185","Long":"-71.3287"},{"zip":"02032","City":"East
Walpole","State":"MA","lat":"42.1548","Long":"-71.2164"},{"zip":"02062","City":"Norwood","State":"MA","lat":"42.1855","Long":"-71.2022"},{"zip":"02071","City":"South
Walpole","State":"MA","lat":"42.105","Long":"-71.2705"},{"zip":"01770","City":"Sherborn","State":"MA","lat":"42.233","Long":"-71.3814"}
You need to have a object that describes your format and use your library to convert it from JSON (dont know about Klaxon but for GSON would be as show in sample)
models in separated files
public class Model {
public String zip, City, State, lat, Long;
}
public class ModeList {
public Model[] towns;
}
Then where you need your values:
List<Model> listOfModel = new Gson().fromJson(yourJsonAsStringHere);
To display in a ListView you use your list of Model to get the number of elements and each element to display one value.
Klaxon is pretty straight-forward you can check the samples into the README from the github https://github.com/cbeust/klaxon
With kotlin you even dont need to build types early.

Serilize custom ArrayList to JSON

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

How to read JSON array and display image in Android

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..

How to start an android project coders view

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

Categories

Resources