ATS : REST Operations - Parsing JSON body

Introduction

JSON (JavaScript Object Notation) is a text-based open standard designed for human-readable data interchange similar to XML and YAML.

In this page we will use mostly the following example:

{
	"firstName":"Indiana",
	"lastName":"Johnes",
	"age":10
}



Different ways to specify the JSON body

Java object:

Person jsonBody = new Person();
jsonBody.setFirstName( "Indiana" );
jsonBody.setLastName( "Johnes" );
jsonBody.setAge( 40 );

This is the easiest to use way, but sometimes the problem is that you do not have the jar with the needed class(in this example this is the Person class).

Simple text:

String jsonBody = "{\"firstName\":\"Indiana\",\"lastName\":\"Johnes\",\"age\":10}";

The formatting here is not always understandable. Additionally it will be very difficult to extract a value from such (String) response.

JSON text:

import com.axway.ats.action.json.JsonText;

JsonText jsonBody = new JsonText();
jsonBody.add( "firstName", "Indiana" );
jsonBody.add( "lastName", "Johnes" );
jsonBody.add( "age", 10 );

In this example we are using our JsonText class provided by ATS. You still do not need the corresponding java class, but the working with this class is much easier compared to regular String.

All presented 3 examples above send the request in the same way:

RestResponse response = client.postObject( jsonBody );



Constructing JsonText

Fetched as body of a response

JsonText jsonBody = client.get().getBodyAsJsonText();

Provide text content when constructing the instance

JsonText jsonBody = new JsonText( "{\"firstName\":\"Indiana\",\"lastName\":\"Johnes\",\"age\":10}" );

Add items one by one

JsonText jsonBody = new JsonText();
jsonBody.add( "firstName", "Indiana" );
jsonBody.add( "lastName", "Johnes" );
jsonBody.add( "age", 10 );

Constructing complex content

Imagine you need to construct a more complex example like the following:

{
	"department" : {
		"totalPeople": 10,
		"people" : [
			{
				"firstName" : "Indiana",
				"lastName" : "Johnes",
				"age":10
			},
			{
				"firstName" : "Will",
				"lastName" : "Smith",
				"age" : 20
			}
		],
		"temperature-this-week" : [20,23,12,11,36]
}

Here is how you can do it:

new JsonText()
	.add( "department",
		new JsonText()
			.add( "totalPeople", 10 )
			.addArray( "people",
				new JsonText[]{
					new JsonText()
						.add( "firstName", "Indiana" )
						.add( "lastName", "Johnes" )
						.add( "age", 10 ),
					new JsonText()
						.add( "firstName", "Will" )
						.add( "lastName", "Smith" )
						.add( "age", 20 )
				}
			)
			.addArray( "temperature-this-week", new int[]{ 20, 23, 12, 11, 36 } )
	);

Note that beside the already presented add method, here we also used the addArray method.

Many JsonText methods return the result instance, so if you want, you can chain as in the example:

JsonText jsonBody = new JsonText().add( "firstName", "Indiana" ).add( "lastName", "Johnes" ).add( "age", 10 );

of course you can always use the other option:

JsonText jsonBody = new JsonText();
jsonBody.add( "firstName", "Indiana" );
jsonBody.add( "lastName", "Johnes" );
jsonBody.add( "age", 10 );

The above java code may look complex, but the actual output is complex too.

Using this approach is good when you are taking some programmatic approach in constructing your JSON body. For example if the input comes from some template file or some user interaction - then you can use this approach to add the needed content.



Retrieving content from JsonText

Here is how you can get some JSON value:

JsonText jsonBody = client.get().getBodyAsJsonText();

// get a String value
String firstName = jsonBody.getString( "firstName" );

// get an int value
int age = jsonBody.getInt( "age" );

Modifying content

You can replace some values in the JSON text:

jsonBody.replace( "firstName", "Will" );

jsonBody.replace( "age", 35 );

Or you can delete some of the content:

jsonBody.remove( "firstName" );

jsonBody.remove( "age" );



Pointing deeper in the content

We are using some simple expression language to point to the right key somewhere inside. Here are some examples:

// this will return 10
jsonBody.getString( "department/totalPeople" );

// this will return "Indiana"
jsonBody.getString( "department/people[0]/firstName" );

// this will return 11
jsonBody.getInt( "department/temperature-this-week[3]" );

All methods use same approach to point to a key of interest - getValue(), replace() or remove()



JSON top level arrays

In some cases you may need to work with JSON content which top level is an array of JSON objects like the following:

[
	{
		"firstName" : "Indiana",
		"lastName" : "Johnes",
		"age":10
	},
	{
		"firstName" : "Will",
		"lastName" : "Smith",
		"age" : 20
	}
]

in this case the first token in the path will be the index of the JSON object:

// this will return Johnes
jsonBody.getString( "[0]/lastName" );

// this will return Smith
jsonBody.getString( "[1]/lastName" );



Nicely formatting the JSON text

You have the option to print the JSON text as regular or as a well formatted text.

For example using the toString() method may give you output like the following:

{"department":{"totalPeople":10,"temperature-this-week":[20,23,12,11,36],"people":[{"lastName":"Johnes","age":10,"firstName":"Indiana"},{"lastName":"Smith","age":20,"firstName":"Will"}]}}

while using the toFormattedString() method for the same JSON text will give you output like the following:

{
	"department":{
		"totalPeople":10,
		"temperature-this-week":[
			20,23,12,11,36
		],
		"people":[
			{
				"lastName":"Johnes",
				"age":10,
				"firstName":"Indiana"
			},
			{
				"lastName":"Smith",
				"age":20,
				"firstName":"Will"
			}
		]
	}
}



Iterating over the JSON text content

If you do not know the content, but want to explore it, you can use the following example as a starting point.

if( jsonBody.isTopLevelObject() ) {
	// we are dealing with a JSON object

	for( String name : jsonBody.getElementNames() ) {
        // here we get the name of the next element

		// do something with the found element, in this case we just print it out
		System.out.println( name + " : " + jsonBody.getString( name ) );

		// or we can navigate to it
		JsonText someJsonText = jsonBody.get( name );
    }
} else {
	// we are dealing with a JSON array

	// get the number of top level elements
	int topLevelNumberOfElements = jsonBody.getNumberOfElements( "" );

	// iterate the top level elements
	for( int i = 0; i < topLevelNumberOfElements; i++ ) {

		// get the next JSON object
		JsonText jsonInternalElement = jsonBody.get( "[" + i + "]" );

		// iterate the elements using their names
		for( String name : jsonInternalElement.getElementNames() ) {

			// do something with the found element, in this case we just print it out
			System.out.println( name + " : " + jsonInternalElement.getString( name ) );
		}
	}
}



Back to parent page

Go to Table of Contents