I am new to ASP.NET MVC and studying. So far, I have figured out how to create a JSON object and return it in response to a request. However, I cannot pass the JSON body as part of the POST request, as I used to use Java .
Here is the code how I did it -
@Path("/storeMovement") @POST @Consumes("application/json") @Produces("application/json") public String storeTrace(String json) { JSONObject response = new JSONObject(); JSONParser parser = new JSONParser(); String ret = ""; try { Object obj = parser.parse(json); JSONObject jsonObj = (JSONObject) obj; RecordMovement re = new RecordMovement((double) jsonObj.get("longitude"), (double) jsonObj.get("latitude"), (long) jsonObj.get("IMSI")); ret = re.Store(); // Clear object re = null; System.gc(); response.put("status", ret); } catch (Exception e) { response.put("status", "fail " + e.toString()); } return response.toJSONString(); }
I tried the same in the ASP.NET action method, but the value of the string a parameter is null , as seen during debugging. Here the action method code is
public string Search(string a) { JObject x = new JObject(); x.Add("Name", a); return x.ToString(); }
It works fine when I use Object (like a book) in the same way -
public string Search(Book a) { JObject x = new JObject(); x.Add("Name", a.Name); return x.ToString(); }
In this case, the name of the book is de-serialized just fine, as I expected. The class definition for the Book class is
public class Book { public int ID { get; set; } public string Name { get; set; } }
Can someone please tell me what I'm doing wrong? Is there no way to take a string and then de-serialize? I would like to be able to accept JSON without using Object
source share