How to implement Post API JSON with Spring?

40 views Asked by At

I'm having difficulty implementing a JSON to send as a POST call in Spring. Which is the fastest and most effective way to turn this json into a java object or a map and make the call? below is an example of a json to send:

{
  "apiVersion": "apps/v1",
  "kind": "Deployment",
  "metadata": {
    "name": "edge-ws"
  },
  "spec": {
    "selector": {
      "matchLabels": {
        "run": "edge-ws"
      }
    },
    "replicas": 1,
    "template": {
      "metadata": {
        "labels": {
          "run": "edge-ws"
        }
      },
      "spec": {
        "containers": [
          {
            "name": "edge-ws",
            "image": "server-tim:latest",
            "imagePullPolicy": "Never",
            "ports": [
              {
                "containerPort": 80
              }
            ]
          }
        ]
      }
    }
  }
}

this and the second body that has a value (nodeport) that must be taken from a field entered by the user front end side.(page created in html)

{
  "apiVersion": "v1",
  "kind": "Service",
  "metadata": {
    "name": "edge-ws",
    "labels": {
      "run": "edge-ws"
    }
  },
  "spec": {
    "type": "NodePort",
    "ports": [
      {
        "port": 8080,
        "targetPort": 80,
        "nodePort": 30200,
        "protocol": "TCP",
        "name": "http"
      }
    ],
    "selector": {
      "run": "edge-ws"
    }
  }
}

Both files must be sent with a single click on a button on the front end side.the first call with the first body starts and if everything is ok the second body starts

What should the class that maps objects look like? What should the controller look like instead? They also gave me an address to call that can only be used on the machine, how can I test this call locally? Thanks in advance!

1

There are 1 answers

0
Soni On

You can use google's Gson library to convert the JsonString to Object and then use below code:

        Gson gson = new Gson();
        Object requestObject = gson.fromJson(jsonString, Object.class);
        ResponseObject responseObject = restTemplate.postForObject(url, requestObject, ResponseObject.class);