Citizens, I apologize, but I don’t even know the name of what I am doing (it is also interesting to know who will understand me). There is something like this JSON request

{ "id":0, "jsonrpc":"2.0", "method":"server.filter.list", "params":{ "locale":1033 } } 

A colleague wrote in C #, created a variable for this query:

 string json = @"{""id"":""0"",""jsonrpc"": ""2.0"",""method"": ""server.filter.list"",""params"": {""locale"": 1033}}"` 

I want to create the same variable correctly for sending the request in the future, BUT only in Java.

Actually the question:

  1. What is this process called?
  2. How do i write on java it?

I will be very grateful. If something is incorrectly written or designed, write immediately can I can explain.

So it will be right?

 String json = "{\"id\":\"0\",\"jsonrpc\": \"2.0\",\"method\": \"server.filter.list\",\"params\": {\"locale\": 1033}}"; 

    1 answer 1

    In the same way, you can assemble the necessary string in Java with "hands". This process is called "string declaration":

     String json = "{\"id\":0,\"jsonrpc\":\"2.0\",\"method\":\"server.filter.list\",\"params\":{\"locale\":1033}}"; 

    However, usually you need to substitute some values, parse the response received and work with strings becomes inconvenient. Therefore, in practice they use libraries - JSON-mappers.

    First, class (s) are created that describe the structure of the JSON message. An instance of such an object is created, fields are filled. Then the library will convert the object into a JSON string. This is called JSON serialization. The inverse process (conversion of a string into an object) is JSON-deserialization. It looks like this for your case:

     private class Request { private Long id; private String jsonrpc; private String method; private Map<String, Object> params; // ... геттеры и сеттеры } // получаем строку Request request = new Request() request.setId(0); request.setJsonrpc("2.0"); request.setMethod("server.filter.list"); Map params = new HashMap(); params.put("locale", Integer.valueOf(1033)); request.setParams(params); ObjectMapper mapper = new ObjectMapper(); String json = mapper.writeToString(request); 

    The concrete implementation of the last two lines depends on the library. Of the most popular, you can mention:


    If you look closely, your request is similar to the message in the JSON-RPC protocol . In this case, it is better to use one of the specialized libraries for this protocol .

    • Yes, this is JSON-RPC. I have been suffering for 4-5 hours and am writing a simple request) - Vorobey.A