掲示板

How to deserialize xxxImp.java using GSON or JSONObject

9年前 に Edgar Trania によって更新されました。

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"
7年前 に Ricardo Jafe によって更新されました。

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

New Member 投稿: 1 参加年月日: 15/05/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!