How to use WebAPI post JSON values having " - c#

public ActionResult<string> Post([FromBody] bot bot)
{
string jsonstr = JsonConvert.SerializeObject(bot);
return jsonstr;
}
public class bot
{
public string bot_id { get; set; }
public string bot_uid { get; set; }
}
Webapi post
JSON Params
{
"bot_id":"XX"XX"
}
if json value has ", how can I create a model to post webapi?

If this is about returning values
If bot id has a double quote in it the json serializer will escape it and there should be no problems.
I suspect you may be misreading the json. Some tools, including Visual Studio's Watch and Local Variables windows and the console window may show escaped " without the backslash and it may appear as if the string is { "bot_id":"XX"XX" } when in fact it's { "bot_id":"XX\"XX" }.
Also, is it possible that XX"XX is XX''XX (with two single quotes)?
In either case JsonCovert will serialise the string correctly.
If this is about consuming json
{ "bot_id":"XX"XX" } is a piece of invalid json.
I think there are two options here
Fix json (preferred)
Ask the poster to fix their payload.
Preprocess the json
You can accept json, fix known issues and only then feed it to the json deserialiser.
ActionResult<string> Post([FromBody] string botJson) // accept body as string
{
string fixedJson = fixMyJson(botJson);
var bot = JsonConvert.SerializeObject<Bot>();
...
Or
async Task<ActionResult<string>> Post()
{
HttpContent requestContent = Request.Content;
string botJson = await requestContent.ReadAsStringAsync();
string fixedJson = fixMyJson(botJson);
var bot = JsonConvert.DeserializeObject<Bot>(fixedJson);
...

Related

Retuning JObject\dynamic with ServiceStack seems to return

I'm trying to take a JSON string from SQL (works fine with SQL json queries, it's stuctured fine in there) and return it through ServiceStack. There's no errors on deserializing it, I can see the object in debug, but the result from the service is just a bunch of blank nested arrays?
//Tried both of these, same result
this.Json = JObject.Parse(json);
/// or
this.Json = JsonConvert.DeserializeObject<dynamic>(json);
///....
public dynamic Json { get; set; }
/// or
public JObject Json { get; set; }
Can't do a POCO because I don't know the structure, just need to poop back out the json blob.
See Service Return Types and Customize HTTP Responses for different ways to return custom responses in ServiceStack.
If you just want to return the JSON from SQL Server as-is, you can return the json string with the JSON Content Type, e.g:
[AddHeader(ContentType = MimeTypes.Json)]
public string Get(RawJson request)
{
//...
return json;
}
Or use a HttpResult if you need to add additional HTTP Headers:
public string Get(RawJson request)
{
return new HttpResult(json) {
ContentType = MimeTypes.Json,
Headers = {
[HttpHeaders.XXX] = "..."
}
};
}
Either way you should annotate your Request DTO that it returns a string so clients know to return the string response as-is:
public class RawJson : IReturn<string> {}
If you want to return the JSON object as part of a larger payload you can use JS Utils JSON.parse() to parse arbitrary JSON in untyped generic collections, e.g:
public string Get(CustomJson request)
{
return new CustomJsonResponse {
Result = JSON.parse(json)
};
}
Where Result is an object, using object does mean that it wont be supported with Add ServiceStack Reference typed clients and clients would just need to parse it as arbitrary JSON, e.g. JSON.parse(json) in JavaScript.

How to bind JSON response from httpClient.PostAsJsonAsync

I can httpClient.PostAsJsonAsync(path, content) fine.
However, this post returns some JSON with details of the response, eg:
{"StatusCode":200,"AccessCode":"92BEEB285ZB47DA","InternalMessage":null}
I need to access the AccessCode.
How can I do this cleanly and efficiently? Can I create an object like this:
public class GIResponse
{
public string StatusCode { get; set; }
public string AccessCode { get; set; }
public string InternalMessage { get; set; }
}
And map it to the result?
Or how would I just traverse the JSON and pull out the AccessCode?
I have searched quite extensively but surprisingly I can't find anything on Google - perhaps as this is the result from a Post, not a Get.
How can I do this?
Provided that you get the responseText using httpResponse.Content.ReadAsStringAsync, you can use Json.NET's JObject and define it as dynamic:
dynamic j = JObject.Parse(#"{""StatusCode"":200,""AccessCode"":""92BEEB285ZB47DA"",""InternalMessage"":null}");
Console.WriteLine(j.AccessCode);
Also you can use JsonConvert:
var result = JsonConvert.Deserialize<MyModel>(resposeText);
Obviously, if you already have a model, you do not read it as a string and you can simply read it as your model:
var result = httpResponse.Content.ReadAsAsync<MyModel>();

How call WebAPI method in MVC and send the json object to it

I need to call this method in MVC controller and pass the UpdateRequest object as json format. how I can do that?
[HttpPost]
[Route("updatecertificate")]
public void updatecertificate([FromBody] UpdateRequest certificatereviewed)
{
loansRepository.updatecertificate(certificatereviewed.Id, certificatereviewed.CertificateReview);
}
and this is the input class:
public class UpdateRequest {
public int Id { get; set; }
public bool CertificateReview { get; set;}
}
this is how I call and send separate variable but now I like to send the class object in json format.
private async Task UpdateFundingCertificateReviewed(int id, bool fundingCertificateReviewed)
{
await httpClient.PostAsync(string.Format("{0}/{1}", LoanApiBaseUrlValue, updatecertificate),null);
}
I personally like Newtonsoft.Json to serialize the object.
private async Task UpdateFundingCertificateReviewed
(int id, bool fundingCertificateReviewed)
{
using (var client = new HttpClient())
{
var url = string.Format("{0}/{1}", LoanApiBaseUrlValue, updatecertificate);
var updateRequest = new UpdateRequest { Id = 1, CertificateReview = true};
var data = JsonConvert.SerializeObject(updateRequest);
await client.PostAsync(url, data);
}
}
FYI: Async without return is not a good practice. However, it is out of the original question.
If you want to transform an object into a JSON string, see this question: Turn C# object into a JSON string in .NET 4
var json = new JavaScriptSerializer().Serialize(obj);
Is this what you are after or do you want to know how to construct the http request with a JSON object in the body?
your questionis not very clear, what is the outcome that you expect ?
If you want to POST an request with JSON body you can check the #Win comment,
however if you want to make an Response from the Api to the MVC project you should do a bit more steps tough. :))

receiving a json string in C# Web Api 2

I'm trying to do a patch with web api. I keep getting NULL for my json. Please Help
Here is my Json
[{"PartNumber":"AN33016UA-VB"}{"Category":"Chassis"}]
Here is my my class
public class wsCategory
{
public string PartNumber { get; set; }
public string Category { get; set; }
}
Here is my Api Controller
[HttpPatch]
[ActionName("IMDSCategory")]
public HttpResponseMessage IMDSCategory([FromBody]wsCategory jsonbody)
{
var data = jsonbody.PartNumber;
return new HttpResponseMessage(HttpStatusCode.Created);
}
The JSON is inavalid.
[{"PartNumber":"blahblah","Category":"Chassis"}]
I believe the array container will be parsed out correctly, but I'm on a chromebook right now, so I can't check that. If it still fails, drop the [].
based on your method
[HttpPatch]
[ActionName("IMDSCategory")]
public HttpResponseMessage IMDSCategory([FromBody]wsCategory jsonbody){...}
Your JSON is invalid given the model you are trying to parse.
[{"PartNumber":"AN33016UA-VB"}{"Category":"Chassis"}]
should be
{"PartNumber":"AN33016UA-VB","Category":"Chassis"}

Can I manually hard code a JSON object to be returned by ASP.NET web API?

I'm used to doing this in Django (similar to Ruby on Rails) where in some cases I need to hard code a JSON response object for the client to be able to interpret, but I've been searching everywhere online on figuring out how to do this with ASP.NET web API and I can't find anything on this, ASP.NET web API seems to be forcing me to create a class to represent a JSON response for every URI controller.
For example, here's the only way I know for manually creating a JSON response:
1.) I first need to create the class to represent the response object
public class XYZ_JSON
{
public string PropertyName { get; set; }
public string PropertyValue { get; set; }
}
2.) Then I need to properly write up the URI controller that'll return an "XYZ_JSON" that I've just defined above:
// GET: api/ReturnJSON
public XYZ_JSON Get()
{
XYZ_JSON test = new XYZ_JSON { PropertyName = "Romulus", PropertyValue = "123123" };
return test;
}
Will result with an http response of something like:
200 OK
{"PropertyName":"Romulus", "PropertyValue":"123123"}
This whole class to JSON design pattern is cool and all, but it's not helpful and actually makes things much worse when trying to return a class as a JSON object with many classes within it such as:
public class XYZ_JSON
{
public string PropertyName { get; set; }
public string PropertyValue { get; set; }
public List<ComplexObject> objects { get; set; } // <- do not want
}
The JSON response object above isn't that complex, but for what I'm trying to accomplish I'll have to put a list of classes within a list of classes within a list of classes, and I can't develop it in this awkward way unless I spend a week on it which is just ridiculous.
I need to be able to return a JSON response in this kind of fashion:
// GET: api/ReturnJSON
public JSON_Response Get(string id)
{
// do some SQL querying here to grab the model or what have you.
if (somethingGoesWrong = true)
return {"result":"fail"}
else
return {"result":"success","value":"some value goes here"}
}
The design pattern above is what I'm trying to accomplish with ASP.NET web API, a very simply way to return a semi-hard coded JSON response object which would allow me to return very unique and dynamic responses from a single URI. There's going to be many use cases where a list of up to 8 completely unique Class objects will be returned.
Also, If what I'm trying to accomplish is the backwards way of doing things than that's fine. I've released a very successful and stable iOS application with a flawless Django backend server handling things this way perfectly without any issues.
Can someone explain to me how I can return a simple hard coded JSON response using the ASP.NET web API?
Thanks!
You can create anonymous types in C#, so you can use one of these to produce your hard-coded result. For example:
return new JsonResult
{
Data = new
{
result = "success",
value = "some value"
}
};
To clarify, the above code is for ASP.NET MVC. If you're using Web API, then you can just return the data object, or use an IHttpActionResult. The anonymous type part (the new {}) stays the same.
Use an anonymous object.
public object Get(string id)
{
// do some SQL querying here to grab the model or what have you.
if (somethingGoesWrong = true)
return new {result = "fail"}
else
return new {result = "success", value= "some value goes here"}
}
You can use a generic JObject to return your values without constructing a complete class structure as shown below
public JObject Get(int id)
{
return JsonConvert.DeserializeObject<JObject>(#"{""result"":""success"",""value"":""some value goes here""}");
}
For hard coded response, why not just do something like below. The JSON content will be returned without being surrounded by quotation marks.
public HttpResponseMessage Get()
{
string content = "Your JSON content";
return BuildResponseWithoutQuotationMarks(content);
}
private HttpResponseMessage BuildResponseWithoutQuotationMarks(string content)
{
var response = Request.CreateResponse(HttpStatusCode.OK);
response.Content = new StringContent(content);
return response;
}
private HttpResponseMessage BuildResponseWithQuotationMarks(string content)
{
var response = Request.CreateResponse(HttpStatusCode.OK, content);
return response;
}
// GET: api/ReturnJSON
public JsonResult Get()
{
return Json(new { Property1 = "Value1", Property2 = "Value2" });
}
You can return json using JsonResult class. and the Json() method takes anonymous object so you don't need to create a class.

Categories