How to serialize ArrayList<Object> to String in Java Android - android

This question was asked many times, but I haven't found a good solution yet.
I want to store my Arraylist in the sharedpreferences in Android as a String. So how can I serialize and deserialize it?
Any solutions?

Try using Gson Library this way:
String json = new Gson().toJson(<your list>);
To add Gson library add to dependencies
compile "com.google.code.gson:gson:2.6.2"

You can supply a toString() method for your custom objects then call toString() on the ArrayList. Parsing the string to deserialize it will be more difficult.

Related

When working with GSON is it mandatory to have classes for JSON objects that are needed to be excluded?

I am trying to use GSON in order to parse a JSON that include some classes and fields that need to be excluded. Do I have to create classes for such objects, and include such fields in classes I create?
As it take Class<object> classOfT as parameter so we have to pass parameter, but if you dont want to make your custom class you can use it by this way.
Gson gson = new Gson();
gson.fromJson("Response Json String", Object.class);
and you can play with that object in many ways.
You can use #Expose annotation for your fields with serialize and deserializeparameters to false
Just don't add the field to the class and ignore it. There is no need to use all input, even with auto-mapping. Whatever has no #SerializedName annotation will not be mapped- #Expose also controls that. But the actual beauty of GSON is parsing such nested nodes to classes of various types.
just see: #SerializedName, #Expose.

Is there any way to directly handle json in android/java without convert [duplicate]

I was wondering if somewhere out there exists a java library able to query a JSONObject. In more depth I'm looking for something like:
String json = "{ data: { data2 : { value : 'hello'}}}";
...
// Somehow we managed to convert json to jsonObject
...
String result = jsonObject.getAsString("data.data2.value");
System.out.println(result);
I expect to get "hello" as output.
So far, the fastest way I have found is using Gson:
jsonObject.getAsJsonObject("data").getAsJsonObject().get("data2").getAsJsonObject("value").getAsString();
It's not actually easy to write and read. Is there something faster?
I've just unexpectedly found very interesting project: JSON Path
JsonPath is to JSON what XPATH is to XML, a simple way to extract parts of a given document.
With this library you can do what you are requesting even easier, then my previous suggestion:
String hello = JsonPath.read(json, "$.data.data2.value");
System.out.println(hello); //prints hello
Hope this might be helpful either.
While not exactly the same, Jackson has Tree Model representation similar to Gson:
JsonNode root = objectMapper.readTree(jsonInput);
return root.get("data").get("data2").get("value").asText();
so you need to traverse it step by step.
EDIT (August 2015)
There actually is now (since Jackson 2.3) support for JSON Pointer expressions with Jackson. So you could alternatively use:
return root.at("/data/data2/value").asText();
First of all, I would recommend consider JSON object binding.
But in case if you get arbitrary JSON objects and you would like process them in the way you described, I would suggest combine Jackson JSON processor along with Apache's Commons Beanutils.
The idea is the following: Jackson by default process all JSON's as java.util.Map instances, meanwhile Commons Beanutils simplifies property access for objects, including arrays and Map supports.
So you may use it something like this:
//actually it is a Map instance with maps-fields within
Object jsonObj = objectMapper.readValue(json, Object.class);
Object hello = PropertyUtils.getProperty(jsonObj, "data.data2.value")
System.out.println(hello); //prints hello
You can use org.json
String json = "{ data: { data2 : { value : 'hello'}}}";
org.json.JSONObject obj = new org.json.JSONObject(json);
System.out.println(obj.query("/data/data2/value"));
I think no way.
Consider a java class
class Student {
Subject subject = new Subject();
}
class Subject {
String name;
}
Here if we want to access subject name then
Student stud = new Student();
stud.subject.name;
We cant access name directly, if so then we will not get correct subject name. Like here:
jsonObject.getAsJsonObject("data")
.getAsJsonObject()
.get("data2")
.getAsJsonObject("value")
.getAsString();
If you want to use same like java object then use
ClassName classObject = new Gson().fromJson(JsonString, ClassName.class);
ClassName must have all fields to match jsonstring. If you have a jsonobject inside a jsonobject then you have to create separate class like I'm doing in Student and Subject class.
Using Java JSON API 1.1.x (javax.json) one can make use of new JavaPointer interface. Instance implementing this interface can be considered to some extend as kind of XPath expression analog (see RFC-6901 for details). So in your case you could write this:
import javax.json.*;
//...
var jp = Json.createPointer("/data/data2/value");
System.out.println(jp.getValue(jsonObject));
In 1.1.4 version of JSON there's also nice addition to JsonStructure interface (which is implemented by JsonObject and JsonArray), namely getValue(String jsonPointer). So it all comes down to this simple one-liner:
System.out.println(jsonObject.getValue("/data/data2/value"));

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 parse json page using gson?

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

Parsing an object with variable type in gson

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.

Categories

Resources