Home > Software engineering >  Get Json Value from text
Get Json Value from text

Time:05-26

i have a rest response, which contains text and json value, i need to get uniqueId from json value, what will be the best way?

My json is very big, but looks like this:

paymentResponse = Published your custom Transaction json to topic env_txn_endtoend_01 Final json: {"txnId":null, "envelope":{"uniqueId":234234_2344432_23442","rootID":"34534554534" etc...}}

How can i get this uniqueId value = 234234_2344432_23442

Thank you

CodePudding user response:

There are many libraries to help with Json Serialization and Deserialization. Jackson Object Mapper is one of the most popular ones.

The code would be something like this. To begin with you would need Java Pojo which represents your json Object e.g. let's consider this example from this tutorial, where you can create a Car Java Object from a Car json string.

ObjectMapper objectMapper = new ObjectMapper();
String json = "{ \"color\" : \"Black\", \"type\" : \"BMW\" }";
Car car = objectMapper.readValue(json, Car.class);  // you should have a Car Class(Pojo) with color, and type attributes

CodePudding user response:

Final json: {"txnId":null, "envelope":{"uniqueId":234234_2344432_23442","rootID":"34534554534" etc...}}

How can i get this uniqueId value = 234234_2344432_23442

You could do something like this:

import groovy.json.JsonSlurper

...

String jsonString = '{"txnId":null, "envelope":{"uniqueId":"234234_2344432_23442","rootID":"34534554534"}}'
def slurper = new JsonSlurper()
def json = slurper.parseText(jsonString)

def envelope = json.envelope

String rootId = envelope.rootID
assert rootId == '34534554534'

String uniqueId = envelope.uniqueId
assert uniqueId == '234234_2344432_23442'
  • Related