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?
Related
I am trying to create a JSON schema validator. My Json schema validates a certain property value and based on that it assigns value to another property. In my C# code I want to perform an action based on that. If you notice in my schema, if country is either "United States of America" or "Canada" then, I am setting effect be "compliant" else "non-complaint". And, In my C# code, I need the value of "effect" so that I can do some further processing. Is that possible? If not, what should be my approach? I am new to Json Schema (I have seen Azure polices doing something similar to this.)
Here is my Schema
{
"type": "object",
"properties": {
"street_address": {
"type": "string"
},
"country": {
"enum": [ "United States of America", "Canada" ]
},
"effect": {"type": "string"}
},
"if": {
"properties": { "country": { "const": "United States of America" } }
},
"then": {
"effect": "Compliant"
},
"else": {
"effect": "Non-Compliant"
}
}
Here is my Document
{
"properties": {
"street_address": "1600 Pennsylvania Avenue NW",
"country": "Canada",
"postal_code": "20500"
}
}
Here is my C# Code
JObject data = null;
var currentDirectory = Directory.GetParent(Environment.CurrentDirectory).Parent.Parent.FullName;
using (StreamReader r = new StreamReader(currentDirectory + #"/Documents/document.json"))
using (JsonTextReader reader = new JsonTextReader(r))
{
data = (JObject)JToken.ReadFrom(reader);
}
JsonSchema schema = JsonSchema.Parse(File.ReadAllText(currentDirectory + #"/Schemas/Schema.json"));
IList<string> messages;
var properties = (JObject)data["properties"];
bool valid = properties.IsValid(schema, out messages);
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.
So this is driving me nuts. I'm doing something very simple sending POST request to my web api. The endpoint is set up as follows:
[HttpPost]
[Route("locations")]
public async Task<IActionResult> PostLocations([FromBody]IEnumerable<Location>locations)
and I'm making the call as follows:
http://localhost:60254/api/Fetch/locations
With the body
{
"Locations": [
{
"LocationId": "111",
"ProductId": 110,
"Sku": "11131-LJK"
}
]
}
And header: content-type: application/json
now again, this is VERY simple something that should work out of the box and this fricking framework change is messing everything up.
Now, if I get the HttpContext and read the body stream directly
using (StreamReader reader = new StreamReader(HttpContext.Request.Body, Encoding.UTF8))
{
string body = reader.ReadToEnd();
}
I can see the body being sent correctly, I have a super well formed json that I can transform into whatever I want. So the question is what am I missing that this endpoint doesn't work?
What configuration the web api project template is not adding out of the box for this to work?
Your payload is not a list of Location but an object with a Locations property that's a list.
Instead of
{
"Locations": [
{
"LocationId": "111",
"ProductId": 110,
"Sku": "11131-LJK"
}
]
}
use
[
{
"LocationId": "111",
"ProductId": 110,
"Sku": "11131-LJK"
}
]
Don't pass a json object, pass a stringified one:
var location = [
{
"LocationId": "111",
"ProductId": 110,
"Sku": "11131-LJK"
}
]
var dataToPost = JSON.stringify(location);
For others...make sure your [FromBody] model and all child classes have parameterless constructors
I am working on a Windows Phone 8.1 application involving location. I am receiving Json data from my API. My API returns data that looks like:
[{
"country": "India",
"city": "Mall Road, Gurgaon",
"area": "Haryana",
"PLZ": "122002",
"street": "",
"house_no": "",
"POI": "",
"type": "17",
"phone": "",
"lng": 77.08972334861755,
"lat": 28.47930118040612,
"formatted_address": "Mall Road, Gurgaon 122002, Haryana, India"
},
{
"country": "India",
"city": "Mall Road, Kanpur",
"area": "Uttar Pradesh",
"PLZ": "208004",
"street": "",
"house_no": "",
"POI": "",
"type": "17",
"phone": "",
"lng": 80.35783410072327,
"lat": 26.46026740300029,
"formatted_address": "Mall Road, Kanpur 208004, Uttar Pradesh, India"
},
{
"country": "India",
"city": "Mall Road Area, Amritsar",
"area": "Punjab",
"PLZ": "143001",
"street": "",
"house_no": "",
"POI": "",
"type": "17",
"phone": "",
"lng": 74.87286686897278,
"lat": 31.64115178002094,
"formatted_address": "Mall Road Area, Amritsar 143001, Punjab, India"
},
{
"country": "India",
"city": "Vasant Kunj (Mall Road Kishan Garh), New Delhi",
"area": "Delhi",
"PLZ": "110070",
"street": "",
"house_no": "",
"POI": "",
"type": "18",
"phone": "",
"lng": 77.1434211730957,
"lat": 28.51363217008815,
"formatted_address": "Vasant Kunj (Mall Road Kishan Garh), New Delhi 110070, Delhi, India"
}]
I am deserializing my Json data and putting it into a class named LocationData. When I run my code, it gives me an error:
Error reading JObject from JsonReader. Current JsonReader item is not an object: StartArray. Path
Where am I going wrong? Here is my code:
private async void GetAPIData()
{
string _serviceUrl = "https://api.myweblinkapiprovider/v2&q=" + UserRequestedLocation;
HttpClient client = new HttpClient();
HttpResponseMessage responce = await client.GetAsync(new Uri(_serviceUrl));
if (responce.Content != null)
{
var respArray = JObject.Parse(await responce.Content.ReadAsStringAsync());
JsonSerializerSettings settings = new JsonSerializerSettings();
settings.NullValueHandling = NullValueHandling.Ignore;
settings.MissingMemberHandling = MissingMemberHandling.Ignore;
var rcvdData = JsonConvert.DeserializeObject<LocationData>(respArray.ToString(), settings);
UpdateMapData(rcvdData);
UpdateTextData(rcvdData);
}
}
I also tried to use a JArray. My code is as below:
private async void GetAPIData()
{
string _serviceUrl = "https://api.myweblinkprovider.com/v3?fun=geocode&lic_key=MyKey" + UserRequestedLocation;
HttpClient client = new HttpClient();
HttpResponseMessage responce = await client.GetAsync(new Uri(_serviceUrl));
JArray arr = JArray.Parse(await responce.Content.ReadAsStringAsync());
foreach (JObject obj in arr.Children<JObject>())
{
JsonSerializerSettings settings = new JsonSerializerSettings();
settings.NullValueHandling = NullValueHandling.Ignore;
settings.MissingMemberHandling = MissingMemberHandling.Ignore;
var rcvdData = JsonConvert.DeserializeObject<LocationData>(arr.ToString(), settings);
UpdateMapData(rcvdData);
UpdateTextData(rcvdData);
}
}
It also gives me an error:
Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'MMI_SpeechRecog.Model.LocationData' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly.
The first part of your question is a duplicate of Why do I get a JsonReaderException with this code?, but the most relevant part from that (my) answer is this:
[A] JObject isn't the elementary base type of everything in JSON.net, but JToken is. So even though you could say,
object i = new int[0];
in C#, you can't say,
JObject i = JObject.Parse("[0, 0, 0]");
in JSON.net.
What you want is JArray.Parse, which will accept the array you're passing it (denoted by the opening [ in your API response). This is what the "StartArray" in the error message is telling you.
As for what happened when you used JArray, you're using arr instead of obj:
var rcvdData = JsonConvert.DeserializeObject<LocationData>(arr /* <-- Here */.ToString(), settings);
Swap that, and I believe it should work.
Although I'd be tempted to deserialize arr directly as an IEnumerable<LocationData>, which would save some code and effort of looping through the array. If you aren't going to use the parsed version separately, it's best to avoid it.
In this case that you know that you have all items in the first place on array you can parse the string to JArray and then parse the first item using JObject.Parse
var jsonArrayString = #"
[
{
""country"": ""India"",
""city"": ""Mall Road, Gurgaon"",
},
{
""country"": ""India"",
""city"": ""Mall Road, Kanpur"",
}
]";
JArray jsonArray = JArray.Parse(jsonArrayString);
dynamic data = JObject.Parse(jsonArray[0].ToString());
I ran into a very similar problem with my Xamarin Windows Phone 8.1 app. The reason JObject.Parse(json) would not work for me was because my Json had a beginning "[" and an ending "]". In order to make it work, I had to remove those two characters. From your example, it looks like you might have the same issue.
jsonResult = jsonResult.TrimStart(new char[] { '[' }).TrimEnd(new char[] { ']' });
I was then able to use the JObject.Parse(jsonResult) and everything worked.
The following worked for me to convert a list of objects to json.
using Newtonsoft.Json;
static void Main(string[] args)
{
List<eventResponse> o = new List<eventResponse>()
{
new eventResponse { acknowledge = "test" } ,
new eventResponse { acknowledge = "test 2" }
};
var json = JsonConvert.SerializeObject(o);
JArray jo = JArray.Parse(json);
Console.WriteLine(jo);
}
public class eventResponse
{
public string acknowledge { get; set; }
}
A delayed answer but if you have access to the API you can work on the javascript object to make it as JSon. Something like
var jsonAddresses = { "addresses":
[
{
"country": "India",
"city": "Mall Road, Gurgaon",
},
{
"country": "India",
"city": "Mall Road, Kanpur",
}
]};
Then in C#
JObject Addjson = JObject.Parse(model.YourAddressesSampleJSONStr);
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);