Global Directory
Global Directory
EXPLORE OUR SITES
London Stock Exchange Group
LSEG Data & Analytics
MyAccount
LSEG Perspectives
London Stock Exchange
FTSE Russell
LCH
Contact Us
Home
TR Internal
How do I deserialize a generic object using fromJson?
Ryan Morlok
How do I deserialize a generic object using the Cobalt infrastructure utility library's JSONHelper.fromJson method? For example, if I have the following (ignoring JSON annotations):
class Foo {
String bar;
}
I can do this:
String json = "{\"bar\":\"abc\"}";
Foo f = JSONHelper.fromJson(json, Foo.class);
But suppose Foo is instead defined:
class Foo {
T bar;
}
How can I deserialize a Foo of T when I know T? E.g.:
Foo f = JSONHelper.fromJson(???)
I see that fromJsonMap and fromJsonList takes a TyperReference object. Do I just need to fall back directly to Jackson the way it's implemented in those methods?
Find more posts tagged with
java
json
refinitiv-internal
Accepted answers
Andrew Gerber
I'm thinking the best approach would to just create your own wrapper around Jackson's `ObjectMapper`. Though you could use a bit of trickery to get what you want out of the JSONHelper's `fromJsonMap` method:
class Foo {
T bar;
}
Map> fooo = JSONHelper.fromJsonMap("{\"foo\":{\"bar\":5}}", new TypeReference>>() {});
System.out.print(fooo.get("foo").bar.equals(5)); // true
Here is a link which shows how to use `TypeReference`:
[
http://www.cowtowncoder.com/blog/archives/2009/01/entry_137.html
][1]
[1]:
http://www.cowtowncoder.com/blog/archives/2009/01/entry_137.html
All comments
Samuel Slotsky
What vertical are you working in? If this is Website code, we typically use `JsonDotNetSerializer.CreateFromJson(string json, bool ignoreMissingMembers)`. Perhaps that would work better for you.
Ryan Morlok
This is in the WebContent module, in Java land.
Samuel Slotsky
In that case, I've not a clue
Andrew Gerber
I'm thinking the best approach would to just create your own wrapper around Jackson's `ObjectMapper`. Though you could use a bit of trickery to get what you want out of the JSONHelper's `fromJsonMap` method:
class Foo {
T bar;
}
Map> fooo = JSONHelper.fromJsonMap("{\"foo\":{\"bar\":5}}", new TypeReference>>() {});
System.out.print(fooo.get("foo").bar.equals(5)); // true
Here is a link which shows how to use `TypeReference`:
[
http://www.cowtowncoder.com/blog/archives/2009/01/entry_137.html
][1]
[1]:
http://www.cowtowncoder.com/blog/archives/2009/01/entry_137.html
Ryan Morlok
This is what I ended up doing only I went straight to Jackson rather than creating a wrapper.
Quick Links
All Forums
Recent Questions
Terms of use
Privacy & Cookie Statement
Cookies settings
Do not sell my info
Whistleblowing
UK Bribery Act
Modern Slavery Act