0

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)

cooldev
  • 497
  • 1
  • 3
  • 17
  • Here is the user guide for JSON-B, it has a lot of good examples in it which you may find helpful: http://json-b.net/docs/user-guide.html – Andy Guibert Nov 18 '20 at 16:34
  • Basically I want to validate the incoming json string – cooldev Nov 19 '20 at 13:37
  • If you want to valid the input of each field I would suggest using `@JsonbCreator` and then you can validate each attribute in the constructor: http://json-b.net/docs/user-guide.html#custom-instantiation – Andy Guibert Nov 19 '20 at 17:47

2 Answers2

0

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();

njr
  • 3,399
  • 9
  • 7
  • It should work for any json string where I am don't have information about the fields – cooldev Nov 19 '20 at 04:23
  • That wasn't clear from the question. I'll add a different answer with an example of how to do that. – njr Nov 19 '20 at 17:44
0

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);
}
njr
  • 3,399
  • 9
  • 7