converting an array in a json string into a list - c#

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

Related

C# - Convert List<JToken> to List<string> one-liner

I got a Json response from a API which contains a JArray in which there is a JProperty named "title".
I have a working one-liner which returns a List<JToken> which stores all the "title" properties of the Json:
List<JToken> queryResult = JObject
.Parse(client.DownloadString(url))["results"]
.Children()["title"]
.ToList();
I tried to edit the above one-liner so it returns a List<string> but without success...
Is there a way to keep it as a one-liner?
A bit too late, but if someone requires.
List<string> stringList = queryResult.Values<string>().ToList();
may do the job.

Convert an array of string into JArray

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);

How to parse a list of Integers from a JSON object

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

De-serialize JSON array in c#

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);

How do I convert a querystring to a json string?

Using server-side C#, how can I convert a querystring to a JSON string of keys and values? For example, I want to convert
"ID=951357852456&FNAME=Jaime&LNAME=Lopez"
to
{ "ID":"951357852456" , "FNAME":"Jaime" , "LNAME":"Lopez" }
I know how to manually parse and format but, before starting down that road, I thought I'd ask since there might be a library that does it better. Thanks!
This gives the exactly same json you want
var dict = HttpUtility.ParseQueryString("ID=951357852456&FNAME=Jaime&LNAME=Lopez");
var json = new JavaScriptSerializer().Serialize(
dict.AllKeys.ToDictionary(k => k, k => dict[k])
);
It also possible to use
var collection = HttpUtility.ParseQueryString(query);
Newtonsoft.Json.JsonConvert.SerializeObject(collection.AllKeys.ToDictionary(y => y, y => collection[y]));
You can use jQuery to do this: jQuery.Param.

Categories