In an Struts 2 project, we need to serialize and deserialize objects, as our requirement is very simple, we decide to use Struts 2 JSONUtil instead of gson.
import org.apache.struts2.json;
String json = JSONUtil.serialize(myAccountVO);
// return: {"accountNumber":"0105069413007","amount":"1500","balance":"215000"}
For deserialization, we face the class cast exception
AccountVO vo =(AccountVO) JSONUtil.deserialize(json);
//Exception
I find that the deserialization returns a map with key value of object properties. So I must do as:
HashMap<String,String> map = (HashMap) JSONUtil.deserialize(string)
accountVo.setAccountNumber(map.get("accountNumber"));
....
Well can I do it better or I am expecting too much from this utility.
After you have deserialized JSON, you can use JSONPopulator to populate bean properties from a map. E.g.
JSONPopulator populator = new JSONPopulator();
AccountVO vo = new AccountVO();
populator.populateObject(vo, map);
What is the way to generate a Java object with get and set methods?
You should write a java bean with properties maching the JSON key's, from that point since you already have a reader its a simple as
YourObject obj = gson.fromJson(br, YourObject.class);
UPDATE
With respect to your comment, when you don't want or can't create a bean it usually boils down to parsing JSON to map. GSON (afaik) doesn't have a built-in for this, but its not hard to build a method that will traverse GSON's objects. You have an example in this blog
http://itsmyviewofthings.blogspot.it/2013/04/jsonconverter-code-that-converts-json.html
As you seem to be open to alternatives, take a look at Jackson as well (the two libs are the de-facto standard in JAVA).
With jackson you don't have to create a bean to support deserialization, e.g.
String json = "{\"id\":\"masterslave\"}";
Map<String,String> map = new HashMap<String,String>();
ObjectMapper mapper = new ObjectMapper();
//convert JSON string to Map
map = mapper.readValue(json,
new TypeReference<HashMap<String,String>>(){});
http://www.jsonschema2pojo.org/
That link helps generate the Java object format based on the GSON you feed in. Just make sure you set the settings exactly as you need it. As always, it's not a good idea to just copy-paste generated code, but it might be of help.
I have the following JSON string.
{"portfolio":"HEXGENFUND","transSrlNo":"1","transCode":"BUY","investReason":"009","inflowOutflow":"I","transDate":"2012-09-01","tradeDate":"2012-09-01","tradeDateUpto":"2012-09-01","tradeTime":"15:46:36","investCategory":"FVTPL","custodian":"DEUTSCHE","holdType":"HOLD","securityType":"INV","security":"9.45SBAI160326","assetClass":"NCD","issuer":"SBAI","marketType":"LIM","tradePriceType":"R","requisitionType":"MS","priceFrom":"343490934332","priceTo":"343490934332","marketPrice":"343490934332","averagePrice":"343490934332","price":"343490934332","quantity":"234","grossAmtTcy":"80376878633688","exchRate":"1","grossAmtPcy":80376878633688,"grossIntTcy":"992.42","grossIntPcy":992.42,"netAmountTcy":80376878634680.42,"netAmountPcy":80376878634680.42,"acquCostTcy":80376878633688,"acquCostPcy":80376878633688,"yieldType":"N","purchaseYield":"0","marketYield":"0","ytm":"-80.07453968","mduration":"0","currPerNav":"0","desiredPerNav":"0","currHolding":"0","noofDays":"0","realGlPcy":0,"realGlTcy":"0","nowLater":"N","isAllocable":"false","acquCostReval":0,"acquCostHisTcy":80376878633688,"acquCostHisPcy":0,"exIntTcy":0,"exIntPcy":0,"accrIntReval":0,"accrIntTcy":0,"accrIntPcy":0,"grossAodTcy":0,"grossAodPcy":0,"grossAodReval":0,"bankAccAmtAcy":80376878634680.42,"bankAccAmtPcy":80376878634680.42,"taxAmountTcy":0,"unrelAmortTcy":0,"unrelAmortPcy":0,"unrelGlTcy":0,"unrelGlPcy":0,"realGlHisTcy":0,"realGlHisPcy":0,"tradeFeesTcy":0,"tradeFeesPcy":0}
I have a POJO for the above.
How do I deserialize this to a Object?
You can use gson library like this to convert above JSON string to HashMap:
Gson gson = new Gson(); // get a new Gson instance
// define a Type for Map<String, String>
Type type = new TypeToken<Map<String, String>>(){}.getType();
// convert JSON string to a Map<String, String> instance
Map<String, String> map = gson.fromJson(jsonStr, type);
EDIT (Based your Edited question): For converting JSON to your POJO object
You can convert JSON string to your custom POJO using gson like this:
// assuming your POJO is of type MyClass
MyClass instance = gson.fromJson(jsonStr, MyClass.class);
If you want to generate the matching java class for the above json string, going with a json generator would be the best solution since the data has many fields.
You may check http://www.jsonschema2pojo.org/
Just paste your json, select JSON as source type and you will have a Jackson compatible annotated java class.
Thake a look at this library tutorial: jackson
String myJson = new org.codehaus.jackson.map.ObjectMapper.writeValueAsString(myObject);
There are some JSON libraries that may helps you.
For example, Gson is a Java library that can be used to convert Java Objects into their JSON representation. It can also be used to convert a JSON string to an equivalent Java object
You can create JSON object by using libraries like gson or JsonOrg. You can take a lokk at the following links for libraries and implementations
https://sites.google.com/site/gson/gson-user-guide
http://code.google.com/p/google-gson/
http://json.org/java/
I've started to using Json with Jackson library and i found little problem.
I'm creating Json object:
ObjectMapper mapper = new ObjectMapper();
Map<String, Object> userInMap = new HashMap<String, Object>();
then i'm adding fields:
userInMap.put("user", "active");
userInMap.put("uuid", uuid);
And after all when im trying to output this object i have Json object but without ", i mean i supposed to have:
{"user":"active", "uuid":"lasdnfa"}
but i have:
{user:active, uuid:lasdnfa}
and another thing - i want to add this object to memcache, but before i do this, i have to serialize this object. How i can serialize Json object?
Thanks
If you are using toString() on your object, you might need your mapper to output the value this way :
System.out.println(mapper.writeValueAsString(userInMap)));
I'm consuming a web service in my application that will return a list of ID's associated with a name. An example would look like this:
{
"6502": "News",
"6503": "Sports",
"6505": "Opinion",
"6501": "Arts",
"6506": "The Statement"
}
How would I construct a POJO for Gson to deserialize to when all of the fields are dynamic?
How about deserializing into a map?
Gson gson = new Gson();
Type mapType = new TypeToken<Map<String, String>>() {}.getType();
String json = "{'6502':'News','6503':'Sports','6505':'Opinion','6501':'Arts','6506':'The Statement'}";
Map<String, String> map = gson.fromJson(json, mapType);
Using a map sounds reasonable for me (as Java is statically typed). Even if this could work (maybe using JavaCompiler) - accessing the object would not probably be much different from accessing a map.
I don't know Gson that well but I suspect that's not possible. You'd have to know which fields are possible beforehand, although the fields might not be in the Json and thus be null.
You might be able to create classes at runtime by parsing the Json string, but I don't know whether that would be worth the hassle.
If everything is dynamic your best bet would be to deserialize the Json string to maps of strings or arrays etc. like other Json libraries do (I don't know whether Gson can do this as well, but the classes you need are commonly called JSONObject and JSONArray).
So your Json string above would then result in a Map<String, String>.