Converting a string to a JSON for a HTTP POST request - c#

I'm trying to return a json file from a HTTP POST request from Slack. I am using netcoreapp3.1 along with the Newtonsoft.Json NuGet. Right now my HTTP POST function looks like this.
public async Task<ActionResult> SlashCommand([FromForm] SlackSlashCommand request)
{
var retVal = new JsonResult(GetBlock());
return retVal;
}
GetBlock() is a function that returns a class that I created. This works currently, but everytime I want to modify the json that it returns, I have to modify that class. I would really love to just have a json in string format that I can copy and paste into my code and then return to Slack in json format.
Is there a way to do this? I've been trying to use JsonConvert.DeserializeObject(str); but I'm using it incorrectly. From what I understand, that function takes in an string and converts it to an object. I need to take in a string and convert it to a Microsoft.AspNetCore.Mvc.ActionResult json.
Any help? Thanks.

An alternative option is to use an anonymous type, which will be less vulnerable to becoming invalid JSON (a simple typo in your JSON string could render the entire block of JSON unreadable):
var data = new
{
blocks = new object[] {
new {
type = "section",
text = new {
type = "plain_text",
text = "Hello!",
emoji = true
}
},
new {
type = "divider"
},
new {
type = "actions",
elements = new object[] {
new {
type = "button",
text = new {
type = "plain_text",
text = "Help"
},
value = "helpButton"
}
}
}
}
};
return new JsonResult(data);
Produces:
{
"blocks": [
{
"type": "section",
"text":
{
"type": "plain_text",
"text": "Hello!",
"emoji": true
}
},
{
"type": "divider"
},
{
"type": "actions",
"elements": [
{
"type": "button",
"text":
{
"type": "plain_text",
"text": "help"
},
"value": "helpButton"
}
]
}
]
}
Try it online

I found an answer.
This is my JSON in string format:
string str = "{\"blocks\": [{\"type\": \"section\",\"text\": {\"type\": \"plain_text\",\"text\": \"Hello!\",\"emoji\": true}},{\"type\": \"divider\"},{\"type\": \"actions\",\"elements\": [{\"type\": \"button\",\"text\": {\"type\": \"plain_text\",\"text\": \"Help\"},\"value\": \"helpButton\"}]}]}";
And then this is my function:
public async Task<ActionResult> SlashCommand([FromForm] SlackSlashCommand request)
{
var retVal = new JsonResult(JsonConvert.DeserializeObject<object>(str));
return retVal;
}
This works quite well. Sorry if I didn't give too much info.

Related

Referencing TargetElements when when authoring Adaptive Cards

I am authoring an Adaptive Card in C# and need to add an Image with a ToggleVisibilityAction. The JSON equivalent is:
{
"type": "Image",
"selectAction": {
"type": "Action.ToggleVisibility",
"title": "expand",
"targetElements": [ "REFERENCE_1", "REFERENCE_2",]
},
"url": "MY_IMAGE_URL",
"altText": "visible"
}
In the above REFERENCE_1 and REFERENCE_2 are the Id fields of the elements I want to target.
When authoring it in C#, I have
new AdaptiveImage()
{
SelectAction = new AdaptiveToggleVisibilityAction()
{
Title = "collapse",
TargetElements = REFERENCE_COLLECTION_HERE,
},
}
My challenge is that the JSON version accepts a string reference with an Id of the TargetElement but the C# version expects a List<AdaptiveTargetElement> where REFERENCE_COLLECTION_HERE is. How do I manage to reference the TargetElement while being able to add it where I want it in my card layout.
You can just use AdaptiveTargetElement objects instead of strings:
new AdaptiveImage()
{
SelectAction = new AdaptiveToggleVisibilityAction()
{
Title = "collapse",
TargetElements = new List<AdaptiveTargetElement>
{
new AdaptiveTargetElement("REFERENCE_1"),
new AdaptiveTargetElement("REFERENCE_2"),
},
},
}
You can see the documentation for them here: https://adaptivecards.io/explorer/TargetElement.html

JSON RPC Parameters C#

I am trying to create a method to send JSONRPC 2.0 commands using newtonsoft. I want to be able to pass parameters ant their values. Here is what I have so far
public void test(params object[] parameters)
{
JObject joe = new JObject();
joe.Add(new JProperty("jsonrpc", "2.0"));
joe.Add(new JProperty("id", "1"));
joe.Add(new JProperty("method", "Component.Set"));
JArray props = new JArray();
foreach (object parameter in parameters)
{
props.Add(parameter);
}
joe.Add(new JProperty("params", props));
string json = JsonConvert.SerializeObject(joe);
}
But my problem is that it only sends the parameter names, I don't know how to pass the values for the paramters
So basically, I am getting this
{
"jsonrpc": "2.0",
"id": "1",
"method": "Component.Set",
"params": [
"Name",
"GO"
]
}
when what I am looking for is something like this
{
"jsonrpc": "2.0",
"id": 1234,
"method": "Component.Set",
"params": {
"Name": "My APM",
"Controls": [
{
"Name": "ent.xfade.gain",
"Value": ‐100.0,
"Ramp": 2.0
}
]
}
}
How can I generate JSON with this format?

Encoding/decoding issue with Facebook json messages. C# parsing

I've download json with my conversations archive. I stuck with odd encoding.
Example of json:
{
"sender_name": "Micha\u00c5\u0082",
"timestamp": 1411741499,
"content": "b\u00c4\u0099d\u00c4\u0099",
"type": "Generic"
},
It should be something like this:
{
"sender_name": "Michał",
"timestamp": 1411741499,
"content": "będę",
"type": "Generic"
},
I'm trying to deserialize it like this:
var result = File.ReadAllText(jsonPath, encodingIn);
JavaScriptSerializer serializer = new JavaScriptSerializer();
serializer.MaxJsonLength = Int32.MaxValue;
var conversation = serializer.Deserialize<Conversation>(System.Net.WebUtility.HtmlDecode(result));
Unfortunately the output is like this:
{
"sender_name": "MichaÅ\u0082",
"timestamp": 1411741499,
"content": "bÄ\u0099dÄ\u0099",
"type": "Generic"
},
Anyone know how Facebook encoding the json? I've tried several methods but without results.
Thanks for your help.
Here is the answer:
private string DecodeString(string text)
{
Encoding targetEncoding = Encoding.GetEncoding("ISO-8859-1");
var unescapeText = System.Text.RegularExpressions.Regex.Unescape(text);
return Encoding.UTF8.GetString(targetEncoding.GetBytes(unescapeText));
}
I've collect all answers, mixed them and here we are. Thank you.

Deserialize JSON response with unknown object names using c# ReadObject()

So i'm trying to deserialise a JSON response implicitly back into a object instance using the following code.
DataContractJsonSerializer jsonSerialiser = new DataContractJsonSerializer(responseType);
responseBase = jsonSerialiser.ReadObject(responseStream);
The response if piped out as a string looks as follows
{
"20170317112739": {
"start": {
"SQ": 4577,
"TS": "2017-03-17T11:26:59",
"FisCode": "_R1-AT1_001/1_SQ4577_2017-03-17T11:26:59_0,00_0,00_0,00_0,00_0,00_vr1zl86Y_49e862eb_rNvvLM3FKh4=_DGZt+z+A3fY8zLlt2E55R8zCD/wf7yw9q/VivAiaNtxNpaTkhlTONAsD6yc+8Vcxwnm/lBalIwEI6GswC04kqg=="
},
"close": {
"SQ": 4667,
"TS": "2017-03-17T11:27:39",
"FisCode": "_R1-AT1_001/1_SQ4667_2017-03-17T11:27:16_0,00_0,00_0,00_0,00_0,00_r/82sV+w_49e862eb_FD/gDnivnes=_LKmvkk5OEoL7EFIebQU73VDVfPGzRGOyKNLlIW1mJkvPpqS0oVdWmqiNGR0cnpT35ArF++XzO1D/q7keTJe4cA=="
}
},
"current": {
"start": {
"SQ": 4670,
"TS": "2017-03-17T11:27:39",
"FisCode": "_R1-AT1_0/1_SQ4670_2017-03-17T11:27:39_0,00_0,00_0,00_0,00_0,00_/agx6rsw_49e862eb_qTh1/lCawvo=_f7yNP/+WUWZCojerZ9fe/wID1gll0I37swEKsauV8h7g8gSCFZ2Ykg45JjkO7BrChCBkl0ewohuGdbP4haLbrQ=="
},
"2017-03": {
"SQ": 4673,
"TS": "2017-03-17T11:27:39",
"FisCode": "_R1-AT1_0/1_SQ4670_2017-03-17T11:27:39_0,00_0,00_0,00_0,00_0,00_/agx6rsw_49e862eb_qTh1/lCawvo=_f7yNP/+WUWZCojerZ9fe/wID1gll0I37swEKsauV8h7g8gSCFZ2Ykg45JjkO7BrChCBkl0ewohuGdbP4haLbrQ=="
}
},
"lic": "0SvXs"
}
Simple responses from the JSON service are no problem i can simply decorate these with [DataContract] and [DataMember].
The problem with this particular service response is that item names such as "2017-03" will change depending on when the call is made to during other months/years.
How do i deal with this in C#?, can someone supply an example of how my class should look?
For the life of me i cannot get this data into my object class!
You can have a dynamic dictionary as suggested in this post Deserialize JSON into C# dynamic object?
Or you can implement something like this with the help of System.Web.Helpers
using (StreamReader r = new StreamReader("sample.json"))
{
string json = r.ReadToEnd();
dynamic data = Json.Decode(json);
Console.WriteLine(data["20170317112739"].start.sq);
}
Here sample.json contains your sample JSON response.

How to parse JSON data

Can anyone tell me how I can parse this data in WCF Service with C#?
{"syncresp": {
"synchdr": {
"sessionref": "1234567890"
"syncref": "20110327T012000"
},
"syncbody": {
"syncedrecs": [
{
"recloc": "plog,0,123",
},
{
"recloc": "plog,0,123",
}
],
"serverdata": [
{
"table": " book",
"action": "new",
"recdata": {
"pnum": "67890",
"fname": "ghgfhn"
"lname": "M"
.
.
.
},
},
{
"table": "pins",
"action": "new",
"recdata": {
"patid": 123,
"insprovid": 5,
"insnum": "X34567",
"effdate": "6/3/2011",
"expdate": "5/3/2012",
"status": "a",
},
},
]
}
}}
If you want to create a data contract which can be used in WCF to consume / generate this kind of data, then take a look at http://blogs.msdn.com/b/carlosfigueira/archive/2011/01/11/inferring-schemas-for-json.aspx - it has a tool which "infers" the corresponding classes which can be used, with the DataContractJsonSerializer, to serialize / deserialize your example.
This is quite simple question, so read some manuals before asking such questions.
First search result in google:
http://blah.winsmarts.com/2009-12-How_to_parse_JSON_from_C-.aspx
JavaScriptSerializer jSerialize = new JavaScriptSerializer();
BusinessObjectType businessObject = jSerialize.Deserialize<BusinessObjectType>(configuration);

Categories

Resources