0

I am trying to send below code as Json array in post request , Here is my Json:

        *{
            "date": "2019-01-01",
            "source": {
                "type": "calendar"
            },
            "device": {
                "type": "mobile"
            }
        }*
    Here is my code
    
        
    
    **JSONArray array1 = new JSONArray();
        JSONArray array2 = new JSONArray();
        JSONObject obj = new JSONObject();
        JSONObject obj2 = new JSONObject();
        JSONObject obj3 = new JSONObject();
    
        obj.put("date","2019-01-01");
        obj2.put("type","calendar");
        obj3.put("type","mobile");
        array1.put(obj2.toString());
    
        obj.put("source",array1.toString());
        obj.put("device",array2.toString());**
    

Now i want to send this object in post request. How do i do that?

HttpRequest request = HttpRequest.newBuilder().POST(obj) 
    

here how can i send the "obj" in post request

1
  • Your code doesn't represent the json you post at the beginning. Also, are you using Java HttpRequest since Java 9 or an external library? Commented Feb 2, 2021 at 13:43

1 Answer 1

1

Using MockMvc, as an example, will be like this:

[...]

ObjectMapper objectMapper;

MvcResult result = 
            mockMvc
                .perform(post(URL)
                .headers(headers)
                .content(objectMapper.writeValueAsString(MY OBJECT)))
                .andDo(print())
                .andExpect(status().isCreated())
                .andReturn();

I've used this example code in my tests project. I guess ObjectMapper will help you! :)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.