Skip to content

Instantly share code, notes, and snippets.

@AdamJHowell
Last active July 10, 2023 20:28
Show Gist options
  • Save AdamJHowell/a50f62f95a394f67d20b150c6259785f to your computer and use it in GitHub Desktop.
Save AdamJHowell/a50f62f95a394f67d20b150c6259785f to your computer and use it in GitHub Desktop.
Jackson JsonNode with "primitive" JSON and JUnit testing of getRequestIdAsString()
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
public class RequestIdHandler
{
ObjectMapper objectMapper = new ObjectMapper();
JsonNode requestId;
public RequestIdHandler( int input ) throws JsonProcessingException
{
this.requestId = objectMapper.readTree( String.valueOf( input ) );
}
public RequestIdHandler( String input ) throws JsonProcessingException
{
this.requestId = objectMapper.readTree( input );
}
public JsonNode getRequestId()
{
return this.requestId;
}
public int getNextRequestId()
{
return this.requestId.asInt() + 1;
}
public int getLastRequestId()
{
return this.requestId.asInt();
}
public String getRequestIdAsString()
{
return this.requestId.asText();
}
public int getRequestIdAsInt()
{
return this.requestId.asInt();
}
public void setRequestId( JsonNode input )
{
this.requestId = input;
}
/**
* This method is working properly.
*
* @throws JsonProcessingException if the requestId cannot be parsed by ObjectMapper.
*/
public void setRequestId( String input ) throws JsonProcessingException
{
this.requestId = objectMapper.readTree( input );
}
/**
* This method is working properly.
*
* @throws JsonProcessingException if the requestId cannot be parsed by ObjectMapper.
*/
public void setRequestId( int input ) throws JsonProcessingException
{
this.requestId = objectMapper.readTree( String.valueOf( input ) );
}
/**
* This method is working properly.
*
* @throws JsonProcessingException if the requestId cannot be parsed by ObjectMapper.
*/
public void incrementRequestId() throws JsonProcessingException
{
if( this.requestId.isInt() )
this.requestId = objectMapper.readTree( String.valueOf( this.requestId.asInt() + 1 ) );
}
/**
* This method is working properly.
*
* @return true if the requestId is an integer type.
*/
public boolean isRequestIdAutoIncrement()
{
return this.requestId.isInt();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment