How to convert String value to Custom Model Object in Java? - java

I have one Model Object. In which, i have multiple values. I want to store this Values in SQLite. But data is large, so i want to store Direct Model object
in databse. So i convert model Object to string and store it into database.
Now, Problem is that how to convert this String value to Model Object.
If you have any idea, please share that with Me.
For example,
Person p = new Person();
p.setname("xyz");
p.setage("18");`
String person=p.toString();
Now How to get this "person" string back to Person "p" model object.
This is my code.
ContentValues values = new ContentValues();
String favorite_id = UUID.randomUUID().toString();
values.put(EMuseumLocalData.KEY_FAVORITE_EXHIBITS_ID, favorite_id);
values.put(EMuseumLocalData.KEY_EXHIBIT_SUBCATEGORY_ITEM_ID, Integer.parseInt(categoryByCustomerList.get(position).getSubCategoryItemID()));
try {
Gson gson = new Gson();
String personString = gson.toJson(getAllCategory.get(position).toString());
values.put(EMuseumLocalData.KEY_EXHIBIT_SUBCATEGORY_ITEM_DATA, personString);
Gson gson1 = new Gson();
CategoryByCustomer categoryByCustomer = gson1.fromJson(personString, categoryByCustomer.getName());
} catch (JSONException e) {
e.printStackTrace();
}

You should use GSON or similar libs for this.
Store to DB
For example If you use GSON
Person p = new Person();
p.setname("xyz");
p.setage("18");
Gson gson = new Gson();
String personString = gson.toJson(p);
Now store this personString to DB.
Read from DB
Get back this object from database, read string from DB and convert it to object like below
String personStringFromDB = READ_LOGIC_OF_DB;
Gson gson = new Gson();
Person p = gson.fromJson(personStringFromDB, Person.class);
For more information, read GSON - Gson Example

Consider using a json string representation of the Model Object. There are many java libraries like Jackson, Gson etc., available to help you with serialization/deserialization part.
Here's a sample code to do this in Jackson
//For conversion of Person object(person) to json String:
String personJsonString = new com.fasterxml.jackson.databind.ObjectMapper().writeValueAsString(person);
//For conversion of json String back to Person object(person)
Person person = new com.fasterxml.jackson.databind.ObjectMapper().readValue(personJsonString, Person.class);

You can make Model Object serializable. You need to store the serialized object in SQLite. When you need it, you just get that serialized object from SOLite and deserialize it.

Related

Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2, jsonSyntax Error

I want to save Hashset Object in to Sharedpreference and than want retrieve that data. I am storing data in to hashset and and converting object in to json using Gson. Actually m storing bitmap in to Hashset. I am able to convert and save Hashsetobject into sharedpreference. I am getting problem when I am retrieving and converting json to Hashset Object.
HashSet<images> img = new HashSet<images>(CIRCLES_LIMIT);
Here is Method For Saving Object in to Sharedpreference.
public void saveString() throws JSONException {
Object spSquare = c.getStringDrawObjImages();
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getContext());
SharedPreferences.Editor editor = sharedPrefs.edit();
Gson gson = new Gson();
String jsonSquare = gson.toJson(spSquare)
editor.putString("kEySquare", jsonSquare);
editor.commit();
}
Method For Retrieving That Object.
public void openString() {
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getContext());
Gson gson = new Gson();
String jsonSquare=sharedPrefs.getString("kEySquare",null);
Type typeSquare = new TypeToken<HashSet<images>>(){}.getType();
HashSet<images> arrayListSquare = gson.fromJson(jsonSquare,typeSquare);`//getting Exception here jsonSyntax Error`
if (arrayListSquare != null) {
img = arrayListSquare;
}
}
As per your comment your json as follows is not in format so that Gson can parse it as you are receiving your circle attribute in string not as json.
{
"img": "[Circle[218.69626, 475.58936, 0,android.graphics.Bitmap#42e13c70,0.0,0.0,0.0,0.0,0.0,0.0,]‌​, Circle[186.74065, 670.43713, 0,android.graphics.Bitmap#42e13c70,0.0,0.0,0.0,0.0,0.0,0.0,]‌​]"
}
So your Json is received as object having only attribute that is img.
and you are parsing it as array. That's error. So contact your back end developer and change json structure accordingly.
You serialise a object and want to deserialise it into a HashSet. That's the problem.
Object spSquare = c.getStringDrawObjImages();
What's the type of spSquare? Suppose it is 'Foo.class', you should deserialise it like this:
Foo foo = gson.fromJson(jsonString, Foo.class);
'foo.img' should be your HashSet

Android/Java - Gson parsing from JSON-string to Object(s) - Date issues

When I use the following piece of code in Android:
// convert JSON string to a List of Product objects
Type listType = new TypeToken<List<Product>>(){}.getType();
p = (List<Product>)new Gson().fromJson(json, listType);
It will convert:
[{"$id":"1","ProductId":17,"Name":"Product1","Price":1.49,"Visible":true},
{"$id":"2","ProductId":19,"Name":"Product2","Price":3.89,"Visible":true},
{"$id":"3","ProductId":20,"Name":"Product3","Price":0.32,"Visible":true}]
To three Product objects with the fields int ProductId, String Name, double Price, boolean Visible, and perhaps some other fields.
When I try the same with Orders (which contains a C# DateTime in the JSON) it fails with a JsonSyntaxException : 2014-05-13T00:00:00
So, my question: How can I successfully convert a JSON String containing a Date-String (2014-05-13T00:00:00), to a Java.util.Date object?
I did try the following:
// convert JSON string to a List of Order objects
Type listType = new TypeToken<List<Order>>(){}.getType();
Gson gson = new GsonBuilder().setDateFormat(DateFormat.FULL).create();
o = (List<Order>)gson.fromJson(json, listType);
and
// convert JSON string to a List of Order objects
Type listType = new TypeToken<List<Order>>(){}.getType();
Gson gson = new GsonBuilder().setDateFormat(DateFormat.FULL, DateFormat.FULL).create();
o = (List<Order>)gson.fromJson(json, listType);
but both didn't work.
NOTE: I Googled a bit and most solutions use serializers & deserializers in both the Java code and used API. But since I can't modify my JSON send from my C# Web API, this isn't an option for me. I can only add things at the receiver's end (my Android App).
PS: I might have a solution, though it's a bit extra work & contains a potentially slowing for-loop: I change the Date Date in my Order-class to String Date (so the Gson parsing will put it in that String-field), then add a Date mDate and after Gson has parsed the complete JSON-array of Orders, I parse the Dates to mDates in a for-loop.. Still, this solution is pretty inefficient, so if anyone know how to do it within GsonBuilder itself I would appreciate it.
Thanks in advance for the responses.
Ok, I was close, but made a small (and pretty obvious) mistake..
Instead of:
Gson gson = new GsonBuilder().setDateFormat(DateFormat.FULL, DateFormat.FULL).create();
I need to use:
Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ss").create();
EDIT:
I now use a deseralizer as well, but only in my Android part. The reason why I changed it is as follows:
When I had a differently formatted date or a date that was null, I would get a JsonParseException on the entire JSON, so none of my Order-Objects were created.
Now that I use this seralizer and a Date appears to be of an invalid format or null, it just makes that Date in the Order-object null, but still converts everything as it should with a resulting Order-list.
Code:
try{
// Convert JSON-string to a List of Order objects
Type listType = new TypeToken<ArrayList<Order>>(){}.getType();
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(Date.class, new JsonDeserializer<Date>() {
DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.ENGLISH);
#Override
public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
try{
return df.parse(json.getAsString());
}
catch(ParseException ex){
return null;
}
}
});
Gson dateGson = gsonBuilder.create();
orders = dateGson.fromJson(json, listType);
}
catch(JsonParseException ex){
ex.printStackTrace();
}

Get JSON key name using GSON

I have a JSON array which contains objects such as this:
{
"bjones": {
"fname": "Betty",
"lname": "Jones",
"password": "ababab",
"level": "manager"
}
}
my User class has a username which would require the JSON object's key to be used. How would I get the key of my JSON object?
What I have now is getting everything and creating a new User object, but leaving the username null. Which is understandable because my JSON object does not contain a key/value pair for "username":"value".
Gson gson = new Gson();
JsonParser p = new JsonParser();
JsonReader file = new JsonReader(new FileReader(this.filename));
JsonObject result = p.parse(file).getAsJsonObject().getAsJsonObject("bjones");
User newUser = gson.fromJson(result, User.class);
// newUser.username = null
// newUser.fname = "Betty"
// newUser.lname = "Jones"
// newUser.password = "ababab"
// newUser.level = "manager"
edit:
I'm trying to insert "bjones" into newUser.username with Gson, sorry for the lack of clarification
Use entrySet to get the keys. Loop through the entries and create a User for every key.
JsonObject result = p.parse(file).getAsJsonObject();
Set<Map.Entry<String, JsonElement>> entrySet = result.entrySet();
for(Map.Entry<String, JsonElement> entry : entrySet) {
User newUser = gson.fromJson(p.getAsJsonObject(entry.getKey()), User.class);
newUser.username = entry.getKey();
//code...
}
Using keySet() directly excludes the necessity in iteration:
ArrayList<String> objectKeys =
new ArrayList<String>(
myJsonObject.keySet());
Your JSON is fairly simple, so even the manual sort of methods (like creating maps of strings etc for type) will work fine.
For complex JSONs(where there are many nested complex objects and lists of other complex objects inside your JSON), you can create POJO for your JSON with some tool like http://www.jsonschema2pojo.org/
And then just :
final Gson gson = new Gson();
final MyJsonModel obj = gson.fromJson(response, MyJsonModel.class);
// Just access your stuff in object. Example
System.out.println(obj.getResponse().getResults().get(0).getId());

Converting JSON Data to a set of Java objects

Is there a tool that generates the JSON objects in Java when given JSON data? This tool would either assume one of the "popular" JSON library or would let you specify the JSON library to be used.
For example with valid JSON data
{
"age":100,
"name":"mkyong.com",
"messages":["msg 1","msg 2","msg 3"]
}
when using "org.json.simple.*" the tool would generate something like this
JSONObject obj = new JSONObject();
obj.put("name", "mkyong.com");
obj.put("age", new Integer(100));
JSONArray list = new JSONArray();
list.add("msg 1");
list.add("msg 2");
list.add("msg 3");
obj.put("messages", list);
With Jackson, it's as simple as using an ObjectMapper and creating a POJO to represent your JSON object:
public class Person {
private int age;
private String name;
private List<String> messages;
// getters/setters
}
And then:
String json = "{\"age\":100,\"name\":\"mkyong.com\",\"messages\":[\"msg 1\",\"msg 2\",\"msg 3\"]}";
ObjectMapper mapper = new ObjectMapper();
Person person = mapper.readValue(json.getBytes(), Person.class);
System.out.println(person.getMessages()); // [msg 1, msg 2, msg 3]
To do the reverse, use writeValue:
Person person = new Person();
person.setAge(100);
// ...
mapper.writeValue(..., person);
Jackson is a popular framework for converting between JSON and Java POJOs.
FlexJson is also a good library similar to jackson that i have tried.
There are also other options like Gson,FastJson and json-lib that you can try.
Please share which one did you like and why.

json Deserializer in to target object

Can you recommend on a Json Deserializer that can deserialize into existing object (merge 2 objects)?
When the user submit a form I want to save that into the db this way:
this is the json from the client:
{"affiliateId":1,"name":"First Affiliate","email":"email#gmail.com","user.userName":"test","user.password":"pass-hashed","employee.employeeId":1}
Affiliate affiliateFromDb = affiliateApi.getFromDbById(1);
SomeDeserialization json = new SomeDeserialization();
affiliateFromDb = json.fromJson(affiliateFromJson , affiliateFromDb );//affiliateFromDb = target bean
Meaning that I want the affiliateFromJson to be interpolated into affiliateFromDb.
And than I will call
affiliateApi.save(affiliateFromDb);
Note that the json contains deep deserialize, user.userName
Thanks
Use Gson! In particular, see the Object Examples.
class BagOfPrimitives {
private int value1 = 1;
private String value2 = "abc";
private transient int value3 = 3;
BagOfPrimitives() {
// no-args constructor
}
}
BagOfPrimitives obj2 = gson.fromJson(json, BagOfPrimitives.class);
The only catch here — but you will have this same problem with any other JSON (de)serializer — is the nonstandard "deep" object format you want to work with. You would have to use something like this instead:
{"affiliateId":1,"name":"First Affiliate","email":"email#gmail.com","user": {"userName":"test","password":"pass-hashed"},"employee.employeeId":1}
http://www.json.org/javadoc/org/json/JSONObject.html
JSONObject jsonResponse = new JSONObject(responseString);

Categories