I have my json as given below which is coming as string. I want to map only two fields in SEGMENT object ex:(TYPE and UN_NUM) to a pojo. I used the following code which is returning null values.
test.json
{
"TEST": {
"NAME": "PART_TRAN",
"VERSION": "9.0",
"ID": "----",
"SEGMENT": {
"TYPE": "R",
"CLIENT_ID": "----",
"UN_NUM": "UN"
}
}
}
test.java
process(new Processor() {
@Override
public void process(Exchange exchange) throws Exception {
String data = exchange.getIn().getBody(String.class);
try{
XmlMapper xmlMapper = new XmlMapper();
JsonNode jsonNode = xmlMapper.readTree(data.toString());
ObjectMapper objectMapper = new ObjectMapper();
String value = objectMapper.writeValueAsString(jsonNode);
logger.info("Converting XML to JSON {}" , value);
SEGMENT seg = objectMapper.readValue(value, SEGMENT.class);
Test test = new Test(seg);
logger.info("Test Object {}" , test);
}catch (JsonParseException e){
e.printStackTrace();
}catch (JsonMappingException e){
e.printStackTrace();
}catch (IOException e){
e.printStackTrace();
}
}
}).
SEGMENT.java
@Data
@JsonIgnoreProperties
public class SEGMENT {
@JsonIgnore
private String TYPE;
@JsonIgnore
private String CLIENT_ID;
@JsonIgnore
private String UN_NUM;
}
Test.java
@Data
public class Test {
private String NAME;
private String VERSION;
private String ID;
private SEGMENT segment;
}
Logs:
: Test Object Test(SEGMENT=SEGMENT(TYPE=null, CLIENT_ID =null,UN_NUM =null))
I just added the SEGMENT class which I'm using to map the json.
There is underscore-java library with methods U.fromJsonMap(json)
and U.get(map, path)
. I am the maintainer of the project.
String jsonData = "{\n"
+ " \"TEST\": {\n"
+ " \"NAME\": \"PART_TRAN\",\n"
+ " \"VERSION\": \"9.0\",\n"
+ " \"ID\": \"----\",\n"
+ " \"SEGMENT\": {\n"
+ " \"TYPE\": \"R\",\n"
+ " \"CLIENT_ID\": \"----\",\n"
+ " \"UN_NUM\": \"UN\"\n"
+ " }"
+ " }"
+ "}";
Map<String, Object> jsonObject = U.fromJsonMap(jsonData);
String type = U.<String>get(jsonObject, "TEST.SEGMENT.TYPE");
String unNum = U.<String>get(jsonObject, "TEST.SEGMENT.UN_NUM");
System.out.println(type);
System.out.println(unNum);
Output:
R
UN