留言板

How to deserialize xxxImp.java using GSON or JSONObject

Edgar Trania,修改在9 年前。

How to deserialize xxxImp.java using GSON or JSONObject

Junior Member 帖子: 37 加入日期: 10-11-13 最近的帖子
Is anyone tried to deseralize any model generated from Service builder successfully usding GSON or com.liferay.portal.kernel.json.JSONObject?
Assuming i have EmployeeImpl.java and it has property of Name and JobTitle
Now below is my code using GSON
String myJson = {"Name:"Edgar C Trania Jr":"JobTitle":"Developer"}
EmployeeImpl e = new Gson().fromJson(myJson),EmployeeImpl.class);
System.out.println(e);//Name and JobTitle will not be printed i dont know why

Also I applied using com.liferay.portal.kernel.json.JSONObject

JSONDeserializer<employeeimpl> des = JSONFactoryUtil.createJSONDeserializer();
EmployeeImpl e = des.deserialize(myJson);
</employeeimpl>

Above code will return
"java.util.HashMap cannot be cast to my.proj.model.impl.EmployeeImpl"
Ricardo Jafe,修改在7 年前。

RE: How to deserialize xxxImp.java using GSON or JSONObject

New Member 发布: 1 加入日期: 15-5-29 最近的帖子
I don't use GSON to serialize the String, but the resulting String object contains a JSON array:

{"products": [{
			"id": 123,
			"quantity": 1,
			},{
			"id": 456,
			"quantity": 1,
			}]}


And I deserialize it successfully with:
     Order order = JSONFactoryUtil.looseDeserialize(jsonObject, Order.class);



My Order object has annotation
@JSON(strict = true)
on top of the class declaration and the fields I want to use have the annotation:
@JSON(include = true)
on the GETTER of the property, that is represented by a List<Product>() object
I also implement the interface Serializable and have a zero parameter constructor.

This should garantee that you are able to deserialize directly to your Java class.

Hope it helps!