Extract specific field from json and deserialize it according to speicific Class<?>

758 Views Asked by At

I have a piece of json string which I would like to extract specific fields, and it field exist I would like to deserialize it into a specific type (Class).

So far I have tried using ObjectMapper, but the problem with it that it designed to work in a way that the input json value is mapped to a designated class type. and in my case I need to take specific fields out of json string and deserialize them to objects.

Next, I've tried JsonParser, it offers more options since I can iterate over a json field-by-field and for each field call 'readValueAs' method. this is almost perfect for me, my problem is that I don't want to go over the json field-by-field, I would like to dynamically tell the parser which field to parse and only then deserialize it into an object.

Here is an example of what I would like to achieve:

Say I have this json { "name" : "Bob", "age" : 21, "status" : false }

I would like only to extract "name"'s value (Bob) and then deserialize it to java.lang.String

How can I do this??

EDIT: I try to describe my flow better: When the app first loads I read the arguments of a specific method using reflection, later when the app receives a json message I would like to parse the message in a way that every key in the json corresponds to one arguments of the method. so I need to deserialize the value of the key from json into an object that matches that argument.

If you know reflection mechanism in JAVA-8 you can get the type of the argument as well as it's name like you wrote it in the code!

Hope this make it clearer....not sure :-)

1

There are 1 best solutions below

0
On

Eventually I've found the answer thanks to the help I've received!!!

The correct method of doing what I needed is ObjectMapper#convertValue, it takes an object and return an object of type Class. it does it in 2 steps: 1st convert the object into json representation and 2nd step is serializing it into Class.