This is my JSON string who represent just a simple List:
{"accelerationsList":"[-3.1769, 3.304, 6.3455997, 3.1701]"}
And this is my C# code to deserialize it:
HttpContent requestContent = Request.Content;
string jsonContent = requestContent.ReadAsStringAsync().Result; // i know about deadlock...
List<float> accelerationsList = new JavaScriptSerializer().Deserialize<List<float>>(jsonContent);
I dont know why my accelerationsList is empty! Any suggestions?
Use Newtonsoft.Json, it makes it clean
string accelerationsListString = Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<string, string>>(jsonContent)["accelerationsList"];
List<float> accelerationsList = Newtonsoft.Json.JsonConvert.DeserializeObject<List<float>>(accelerationsListString);
you get the list of float in a string, so we need to convert the string to list after extracting
I believe you have most of what you are looking for except for 1 issue.
you are trying to convert the entire content (json string) to List. You need to convert the json object properly to get the value of accelerationsList, then convert the string that is your List of Floats properly.
string jsonContent = #"{""accelerationsList"":""[-3.1769, 3.304, 6.3455997, 3.1701]""}";
var stringRepOfArray = JObject.Parse(jsonContent)["accelerationsList"].ToString();
List<float> floatList = new JavaScriptSerializer().Deserialize<List<float>>(stringRepOfArray);
Output:
floatList
Count = 4
[0]: -3.1769
[1]: 3.304
[2]: 6.34559965
[3]: 3.1701
Related
I have a piece of code, which should grab info from a URL. Get the value called lowest_price and then parse it into a variable, but there is a $ sign in the JSON so I had to remove it and after that I can't Parse the JSON correctly.
My code:
var tokenPrice = JObject.Parse(steamMarket).ToString().Replace("$", " ");
double marketPrice = tokenPrice["lowest_price"];
JSON
{"success":true,"lowest_price":"$5.61","volume":"6","median_price":"$5.61"}
Error:
Argument 1: cannot convert from 'string' to 'int'
double marketPrice = double.Parse(JObject.Parse(steamMarket)["lowest_price"].ToString().Replace("$", ""));
You can also do:
string json = "{\"success\":true,\"lowest_price\":\"$5.61\",\"volume\":\"6\",\"median_price\":\"$5.61\"}";
var jObject = Newtonsoft.Json.Linq.JObject.Parse(json);
double tokenPrice = double.Parse((string )jObject["lowest_price"], NumberStyles.Currency, new CultureInfo("en-US"));
tokenPrice["lowest_price"] is a string and c# will not automatically convert types for you.
var tokenPrice = JObject.Parse(steamMarket);
double marketPrice = double.Parse(tokenPrice["lowest_price"].ToString().Replace("$", ""));
I have this json string passed to my webapi
string jsonstring = "{\"datamodel\": \"[{\"K1\":\"V1\",\"K2\":\"V2\"}]\"}";
I may have more than on pair of (K,V) inside. How do i parse this in C# ?
I thought i could first convert my string to a JObject and get the key for datamodel from that and then use JArray to parse the K,V. But its throwing a jsonreader exception on the first line of code here
JObject my_obj = JsonConvert.DeserializeObject<JObject>(jsonstring.ToString());
and then do this..
JObject data = my_obj["datamodel"].Value<JObject>();
First of all, the JSON string you are posting is not valid. Given your comment, you can clean up the quotes before and after the square brackets using this snippet:
string jsonstring = "{\"datamodel\": \"[{\"K1\":\"V1\",\"K2\":\"V2\"}]\"}";;
string jsonstringCleaned = jsonstring.Replace("\"[", "[").Replace("]\"", "]");
var my_obj = JsonConvert.DeserializeObject<JObject>(jsonstringCleaned);
The code is right, but the exception you are getting is related to the formatting of your JSON string. If you put valid JSON in this code, it should work as expected.
There are \" missing around V1 in your JSON string.
It should look like this:
string jsonstring = "{\"datamodel\": \"[{\"K1\":\"V1\",\"K2\":\"V2\"}]\"}";
First always make sure that you have a valid Json string. A simple way to do that is paste it into a Json to C# converter tool, such as this one: http://json2csharp.com/
It may be simpler and more readable to use single quotes within your Json string if that is an option, as it avoids the need to escape the double quotes:
string jsonstring = "{'datamodel': [{'K1':'V1','K2':'V2'}]}"
Now we deserialize the object and get the JArray. There is no need to call the ToString() on the JSON jsonstring string.
var my_obj = JsonConvert.DeserializeObject<JObject>(jsonstring);
var data = (JArray)my_obj["datamodel"];
A better and more concise way to accomplish the same result could be to just use JObject.Parse. We can accomplish the same result with just one line of code.
var data = (JArray)JObject.Parse(jsonstring)["datamodel"];
I am trying to serialize a string array into JSON and I am using Newtonsoft JSON.Net for this but the output is wrong and I don't know how to serialize it properly.
I use this code:
string[] subscriptions = new string[] { "downloads" };
string[] exclusion = new string[] { "REFRESH_CONTENT" };
var toSend = new string[][] { subscriptions, exclusion };
string json = Newtonsoft.Json.JsonConvert.SerializeObject(toSend);
And I get this result:
params: [[\"downloads\"],[\"REFRESH_CONTENT\"]]
But I need to get this result:
params: [\"[\\\"downloads\\\"]\",\"[\\\"REFRESH_CONTENT\\\"]\"]
or without escaped strings (to be sure there is no error in the line above):
params: ["[\"downloads\"]","[\"REFRESH_CONTENT\"]"]
Thanks!
Your expectations are wrong. Your toSend is an array of string arrays. And this is what the serialization produces. If you want to get an array of strings, you have to create one:
var toSend = new string[] {JsonConvert.SerializeObject(subscriptions), JsonConvert.SerializeObject(exclusion)};
string json = JsonConvert.SerializeObject(toSend);
But this way, you'll have to parse each element of the array at the receiver side.
I have a page which receives a list of dates in the following format via ajax:
["2015-06-02T23:00:00.000Z","2015-06-03T23:00:00.000Z","2015-06-04T23:00:00.000Z","2015-06-05T23:00:00.000Z"]
I have written the following code to split the dates out:
string input;
using(var reader = new StreamReader(Request.InputStream)){
input = reader.ReadToEnd();
}
string [] arr = input.Split(new string[] {","},StringSplitOptions.None);
but i need to remove the "T23:00:00.000Z" from each date. Can anyone assist?
string [] arr = input.Replace("T23:00:00.000Z","").Split(new string[] {","},StringSplitOptions.None);
This looks like a JSON array of dates. In which case using Json.NET you could just do:
DateTime[] dates = JsonConvert.DeserializeObject<DateTime[]>(*date array string*);
You're then free to do what you want with the new date array.
Its look like json array of dates. Try to deserialize it with JSON.NET library (can found it in NuGet):
var jsonString = "["2015-06-02T23:00:00.000Z","2015-06-03T23:00:00.000Z","2015-06-04T23:00:00.000Z","2015-06-05T23:00:00.000Z"]";
var result = JsonConvert.Deserialize<DateTime[]>(jsonString);
I have this string:
string s = "[\"default\",\"direct\"]";
I want to make an array, so the final array should be this:
["default", "direct"]
What I have tried:
string[] ss = s.Split(',');
But the result is:
What you have is JSON array. You can simply deserialize it with JSON.NET (you can add it from NuGet):
string s = "[\"default\",\"direct\"]";
string[] result = JsonConvert.DeserializeObject<string[]>(s);
you can also use the JArray.
Newtonsoft.Json.Linq.JArray jsonarr = Newtonsoft.Json.Linq.JArray.Parse(jsonResult);