JRPC Demo

JRPC is a Java JSON-RPC over HTTP mini framework. Read more

Examples:

Send and receive numbers

+ =

Here is the client side code:

        let url = '/jrpc/demo/AddNumbers';
        let data = {dataType: "Integer", data: [firstNumber, secondNumber]};
        $.ajax({
            url: url,
            type: "POST",
            data: JSON.stringify(data),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (response) {
                main.view.showAddNumbersResult(response.data[0]);
            }
        });
                

Server side code that we need to write to handle above request consist of class AddNumbers that implements JrpcMethod interface:

    public class AddNumbers implements JrpcMethod{

    @Override
    public ResponseJsonObject execute(HttpServletRequest request, 
             HttpServletResponse response, RequestJsonObject requestJsonObject) {
        Integer[] numbers = (Integer[])requestJsonObject.data;
        int result = numbers[0] + numbers[1];
        ResponseJsonObject responseJsonObject = new ResponseJsonObject();
        responseJsonObject.data = new Integer[]{result};
        return responseJsonObject;
    }    
}
                



Send and receive strings

In this example we will submit any three words to the server, then get them back and display.

     

Here is the client side code:

        submitWords: function (firstWord, secondWord, thirdWord) {
        let url = '/jrpc/demo/EchoWords';
        let data = {dataType: "String", data: [firstWord, secondWord, thirdWord]};
        $.ajax({
            url: url,
            type: "POST",
            data: JSON.stringify(data),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (response) {
                main.view.showSentence(response.data);
            }
        });
    }
                

Notice, that we changed dataType to String.

Here is the server-side code:

    public class EchoWords implements JrpcMethod{

    @Override
    public ResponseJsonObject execute(HttpServletRequest request, 
             HttpServletResponse response, RequestJsonObject requestJsonObject) {
        String[] words = (String[])requestJsonObject.data;
        ResponseJsonObject responseJsonObject = new ResponseJsonObject();
        responseJsonObject.data = words;
        return responseJsonObject;
    }    
}
                



Send and receive objects

Let's say we have a list of users and we want to filter them by age and/or gender

18 and older
Male only Female only

Name Age Gender

We send JSON in request like follow:
[{"type": "age", "value:18"}, {"type": "gender", "value":1} ]

To deserialize JSON on the server side we use next Java class:

    public class UserFilter {
    public String type;
    public int value;
  }
            

Here is the client side code that sends request:

        getUsersByFilters: function () {
        let url = '/jrpc/demo/GetUsersByFilters';
        let data = {dataType: "UserFilter", data: main.model.filters};
        $.ajax({
            url: url,
            type: "POST",
            data: JSON.stringify(data),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (response) {
                main.view.showUsers(response.data);
            }
        });
    }
            

Notice, that we changed dataType to UserFilter.

Here is the server-side code:

    public class GetUsersByFilters implements JrpcMethod{

    @Override
    public ResponseJsonObject execute(HttpServletRequest request, 
             HttpServletResponse response, RequestJsonObject requestJsonObject) {
        UserFilter[] filters = (UserFilter[])requestJsonObject.data;
        User [] users = UserManager.getByFilters(filters);
        ResponseJsonObject responseJsonObject = new ResponseJsonObject();
        responseJsonObject.data = users;
        return responseJsonObject;
    }    
}
            

Here is the User class. For the purpose of this tutorial it was made as simple as possible:

public class User {
    public String name;
    public int age;
    public boolean isMale;
    
    public User (String name, int age, boolean isMale){
        this.name = name;
        this.age = age;
        this.isMale = isMale;
    }
}
            

JRPC uses Gson to deserialize JSON into Java objects and serialize Java objects into JSON. We don't need to explicitly write this conversion code - JRPC does it for us. But we should write Java class that mapped to the JSON and those classes can become complicated in real app. Here is an example of more-less real world JSON representing an online order:

[{
	"id": "Z000000001",
	"totalPrice": 546.34,
	"date": "15.01.2022",
	"customer": {
		"id": "U00000032",
		"name": "John Smith",
		"address": {
			"country": "UK",
			"city": "London",
			"zipCode": "00001",
			"street": "Bakers",
			"buildingNumber": 123
		}
	},
	"products": [{
		"id": "P000000345",
		"price": 234.18,
		"title": "Smartphone Xiaomi 10S",
		"sku": "sku000000023423"
	},
	{
		"id": "P000000347",
		"price": 312.16,
		"title": "Smartphone Samsung S21",
		"sku": "sku000000023424"
	}]
}]
            

In order for JRPC to parse above JSON we should specify dataType: "Order" and have an Order class in our data package on the server side like this:

public class Order {
    public String id;
    public double totalPrice;
    public String date;
    public Customer customer;
    public Product[] products;
    
    
    class Customer{
        public String id;
        public String name;
        public Address address;
    }
    
    class Address {
        public String country;
        public String city;
        public String zipCode;
        public String street;
        public int buildingNumber;
    }
    
    class Product {
        public String id;
        public double price;
        public String title;
        public String sku;
    }
    
}
            


You can read more about JRPC here. Take code from here. Happy coding!