I need to use a JsonParser twice, once to validate the format of my JsonStream by the json schema given..., then I need to contruct my object 'Product'.
The problem is that if I use the parser once, I cannot re-use it a second time. It's like it loses its data values .
Here is my Original code where I construct my Product object using the parser.. :
import javax.json.bind.serializer.DeserializationContext;
import javax.json.bind.serializer.JsonbDeserializer;
import javax.json.stream.JsonParser;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
public class ProductDeserializer implements JsonbDeserializer<Product>
{
@Override
public Product deserialize(final JsonParser parser, final DeserializationContext ctx, final Type rtType)
{
Product product = new Product();
while (parser.hasNext())
{
JsonParser.Event event = parser.next();
if (event == JsonParser.Event.KEY_NAME && parser.getString().equals("productNumber"))
{
parser.next();
product.setProductNumber(parser.getString());
This works fine But I need to include this validation of the json format first..:
ObjectMapper objectMapper = new ObjectMapper();
JsonSchemaFactory schemaFactory = JsonSchemaFactory.getInstance(SpecVersion.VersionFlag.V201909);
String schemaStream = "My json schema here..";
JsonNode json = null;
try
{
json = objectMapper.readTree(parser.getObject().toString());
}
catch (JsonProcessingException eParam)
{
eParam.printStackTrace();
}
JsonSchema schema = schemaFactory.getSchema(schemaStream);
Set<ValidationMessage> validationResult = schema.validate(json);
if (validationResult.isEmpty()) {
System.out.println("no validation errors ");
} else {
System.out.println("There are validation errors ");
}
So if I try to include this part then the contruction of my Product Object will not work anymore and the Product will be null..
So my question is how can I use the parser twice in the same method .. Thanks a lot in advance..