I have an array of string
var ids = new string[]
{
"1408576188",
"1750854738",
"100001058197465"
};
I want to pass this array of string as a json array into an API. For now, the API cannot accept the string returned from :
JsonConvert.SerializeObject(ids);
So I am figuring out that I am able to use the API by turning my ids array into a JArray object.
JArray.Parse(JsonConvert.SerializeObject(ids));
As you can see, I am doing a two operation in here, first I serialize the ids array, then I parse the result into JArray. Is there any way to convert my ids array directly into JArray object?
Did you try the FromObject method:
var array = JArray.FromObject(ids);
Related
I would highly appreciate if someone helped me out with constructing a JArray in C# by only using values and no key. Here is an example of the what I want:
{[
"ZGVyZWtAcG9zc2tpLmNvbQ==",
"YW5kcmVAbGltYWcubmV0",
"YW5keUBiYW9iYW9tYWlsLmNvbQ==",
"dGVzdEBraW5ub3YuY29t",
"c2hhaG5hd2F6LmFsYW0xM0Bob3RtYWlsLmNvbQ==",
"YnJlYW5uQGVtYWlsLmNvbQ=="
]}
Here is the code I wrote for it but I am getting an exception because when I declare JObject, it requires me to have a key and a value, but i only need the value as I am sending this array as a parameter to an API, and they need it in a specific format.
Here is my code that causes the issue:
var recipients = new JArray();
foreach (var c in retrievedContacts.recipients)
{
var jsonObject = new JObject();
jsonObject.Add(c.id);
recipients.Add(jsonObject);
}
dynamic addToListResponse = await sg.client.contactdb.lists._(listJson.lists[0].id).recipients.post(requestBody: recipients);
The last line sends a post request to SendGrid. Here the list id is valid, everything is ok except for adding json object in the loop. Please Help!
To create a JArray with specified values, you can use JToken.FromObject() to convert your c.id to a JToken, then construct your JArray as follows:
var recipients = new JArray(retrievedContacts.recipients.Select(c => JToken.FromObject(c.id)));
In particular, this works if id is a byte array. In this case Json.Net will convert it to a base64 string. Sample fiddle.
If c.id is already a string (in your question, you don't specify its type), you can skip the call to FromObject() and add it as-is without serialization:
var recipients = new JArray(retrievedContacts.recipients.Select(c => c.id));
I'm using "Newtonsoft.Json.Linq.JObject" in my application.
I have a method that receives a JObject in the format:
{
"PersonnelIds": "[31,32,33,34]"
}
And I want to parse the content of PersonnelIds to a List of Integers.
What is the best way of doing that?
I can see that the values of the PersonnelIds is written as string "[31,32,33,34]" so to parse it with this syntax you can use the following code
JObject jObject = JObject.Parse(myjson);
JToken jToken = jObject.GetValue("PersonnelIds");
var array = JArray.Parse(jToken.Value<string>()).Select(x => (int)x).ToArray();
if your value is not string so your JSON is like {"PersonnelIds": [31,32,33,34]
} then you can parse it using the following code
JObject jObject = JObject.Parse(myjson);
JToken jToken = jObject.GetValue("PersonnelIds");
int[] array = jToken.Values<int>().ToArray();
Create a class to deserialize your json:
To create classes, you can copy the json in clipboard and use the
Edit / Paste special / Paste JSON as class
in visual studio (I use vs2013).
Then deserialize your string.
See my solution on this post
I have a very odd JSON array as follows
[["1","hello"],["2","hello2"],["3","hello3"],["",""],["",""],[null,null],[null,null],[null,null],[null,null],[null,null]]
I need to de-serialize in c# but there doesn't seem to be anything common to convert it to I tried string but then I get the follow error:
Type string is not supported for deserialization of an array.
This is the code I tried:
string jsonString = new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize<string>(json);
How would you get at the strings in the JSON?
You could deserialize it to an array of string arrays:
string[][] jsonString = new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize<string[][]>(json);
Or maybe a list of string-tuples (Dictionary could be problematic due to the lack of unique keys):
List<Tuple<string, string>> jsonString = new System.Web.Script.Serialization.JavaScriptSerializer().Deserialze<List<Tuple<string, string>>(json);
I'm having problems passing an array parameter to my .ashx handler. Querystring parameters work fine, but I don't know how to access the array from within the ashx file.
My array is a list of strings called list. This is how I call the getJSON method:
jQuery.getJSON('Handlers/AccessoryUpdateHandler.ashx?action=updateselection&a=' + a_sku, function (list) {
//...
});
In AccessoryUpdateHandler.ashx I can get the querystring parameter using context.Request.QueryString["a"];
But how do I get the array data? I've looked at the Request.QueryString object but there's nothing there that looks like my array.
If there's a better way of doing this I'd also be interested to know.
Perhaps you shouldn't rely on QueryString to pass the kind of data. I would advice you to use "POST" method instead. In either case, using the approach you are using, you wont be able to pass the data as an array. Convert the array into a string. A utility like stringify() can come in handy here if you dont want to convert the array into a string manually. When you extract the string from the Request.QueryString or Request.Form (in case you use post) in the handler, you can easily use JavaScriptSerializer to deserialize using a simple C# class that has a schema similar to your json array.
Edited: Illustration
An array like:
var ary = [{ "id": "1", "name": "Mark" }, { "id": "2", "name": "John"}];
can be converted to a string like:
var aryS = "[{\"id\":\"1\",\"name\":\"Mark\"},{\"id\":\"1\",\"name\":\"Mark\"}]";
then, your QueryString can be constructed as:
jQuery.getJSON('Handlers/AccessoryUpdateHandler.ashx?action=updateselection&a=' + aryS, function (list) {
//...
});
when you go to your handler code, you can have a simple class to help you deserialize the data:
class Rec
{
public int Id { get; set; }
public string Name { get; set; }
}
with that in place, the last step to deserialize is:
string s = context.Request.QueryString["a"]; // HttpContext context
var jserializer = new JavaScriptSerializer();
var ary = jserializer.Deserialize<Rec[]>(s);
Note you have to use Rec[] in the Deserialize function since you are deserializing into an array. ary will be an array of Rec with all your data from your javascript array. You need to reference System.Web.Extensions to use JavaScriptSerializer
EDIT:
I thought you were talking about an array of objects. If its just an array of *long*s, the following lines should be sufficient:
string s = context.Request.QueryString["a"]; // HttpContext context
var jserializer = new JavaScriptSerializer();
var ary = jserializer.Deserialize<long[]>(s);
and you dont need to create a class. you would only need that if you had a array of json objects
I don't think your need for passing arrays should dictate whether you use get or post as others suggest.
Using get, the most idiomatic ways is using the same parameter multiple times. e.g.
Handlers/AccessoryUpdateHandler.ashx?a=1&a=2&a=55
In fact in most frameworks(.NET being the exception) when you get a parameter from url you get a array return(often with one item)
My suggestion is you parse context.Request.RawUrl
I have an array in a json string like this:
"TheArray": "1,2,3,4,5"
What's the best way convert this into a list of int?
Thanks.
string theArray = "1,2,3,4,5";
List<int> theList = (
from string s in theArray.Split(',')
select Convert.ToInt32(s)
).ToList<int>();
Use JSON.Net or JavascriptSerializer, something like:
JArray jsonArray = JArray.Parse(jsonStr);
and then you can get out TheArray from that.
The TheArray in your question is not exactly a JSON array, so you will have to parse the string like other answers suggested after you get value of TheArray
http://www.nateirwin.net/2008/11/20/json-array-to-c-using-jsonnet/
http://james.newtonking.com/projects/json-net.aspx
Parsing JSON using Json.net
You can use the split method:
var items = myObj.TheArray.split(',');
items[0] == "1" // true