Checking json fields using json-b api

82 Views Asked by At

I am using json binding API to parse json string for application deployed on Liberty application server.

Suppose I have json string as given below

String message = "{ "color" : "Black", "type" : "BMW" }";

I want to iterate through json string and check every json property field (color/type) in the application logic to see if it contains some specific characters.

How can this be done using the json-b (Json Binding API)

2

There are 2 best solutions below

2
njr On

Here is a simple example:

public class Car {
    public String color;
    public String type;
}

...

Jsonb jsonb = JsonbBuilder.create();
Car car = jsonb.fromJson("{ \"color\" : \"Black\", \"type\" : \"BMW\" }", Car.class);
if (car.color.contains("Bla") || car.type.startsWith("B"))
    System.out.println("Found a " + car.type + " that is " + car.color);
jsonb.close();

0
njr On

Per section 3.11 of the JSON-B specification, implementations of JSON-B must support binding to java.util.LinkedHashMap (and a number of other standard collection types), so you can do the following if you don't know what the names of the fields are:

Jsonb jsonb = JsonbBuilder.create();
LinkedHashMap<String, ?> map = jsonb.fromJson("{ \"color\" : \"Black\", \"type\" : \"BMW\" }", LinkedHashMap.class);
for (Map.Entry<String, ?> entry : map.entrySet()) {
    Object value = entry.getValue();
    if (value instanceof String && ((String) value).contains("Black"))
        System.out.println("Found " + entry.getKey() + " with value of " + value + " in " + map);
}