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.
Related
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
I'm trying to convert a json string to a string array
my json string: "[\"false\",\"true\"]"
var js = new System.Web.Script.Serialization.JavaScriptSerializer();
string[] strArray = new string[2];
strArray = js.Deserialize("[\"false\",\"true\"]", string[2]).ToArray();
but it only allows me to do a charArray.
I just need to be able to call my result as strArray[0] so that it will return "false"
Try doing:
strArray = js.Deserialize<string[]>("[\"false\",\"true\"]");
Your example code wouldn't compile. The second parameter should be a Type object, which string[2] isn't. It should be this:
strArray = js.Deserialize("[\"false\",\"true\"]", typeof(string[]));
Or, as the other answer mentioned, you can use the other, generic overload for the method:
strArray = js.Deserialize<string[]>("[\"false\",\"true\"]");
Either one will do exactly the same thing. It's just handy to be able to pass a Type object sometimes if you don't know beforehand what the actual type will be. In this case you do, so it doesn't matter.
Why not use Newtonsoft's JArray type? It is built for this conversion and can handle many edge cases automatically.
var jArray = JArray.Parse("[\"false\",\"true\"]");
var strArray = jArray.ToObject<string[]>()
This will give you a string array. But you could also elect to use .ToArray() to convert to a JToken array which can sometimes be more useful.
Is this json data format?
string json = {"answer":"Line 1","mark": 1},{"answer":"Line 3","mark": 1}
I try below code but it only working with one param. ex: {"answer":"Line 1","mark": 1}. I try split json string but it isn't best way.
JObject jObject = JObject.Parse(json );
string asw = jObject["answer"].ToString();
int mark = (int)jObject["mark"];
txtAnswer.Text = asw + "////" + mark + "\n";
This is a very basic JSON question which any number of tutorials could've answered for you.
Is it valid JSON ? No, and JSONLint could've told you that.
How do you read it in ?
First, wrap your JSON in square brackets so it's valid.
Then, define a class to store the records in:
public class Something
{
public string answer { get; set; }
public string mark { get; set; }
}
And finally, use JSON.Net to convert your string into a list of these records.
string json = "[{\"answer\":\"Line 1\",\"mark\": 1},{\"answer\":\"Line 3\",\"mark\": 1}]";
List<Something> records = JsonConvert.DeserializeObject<List<Something>>(json); // JSON.Net
foreach (Something record in records)
{
System.Diagnostics.Trace.WriteLine(string.Format("Answer: {0}, Mark: {1}", record.answer, record.mark));
}
Easy as that.
Is this json data format?
string json = {"answer":"Line 1","mark": 1},{"answer":"Line 3","mark": 1}
Nope, what you've got there doesn't look like valid C# or JSON. Try putting it inside a JSON array, then inside a proper string:
string json = "[{\"answer\":\"Line 1\",\"mark\": 1},{\"answer\":\"Line 3\",\"mark\": 1}]";
(Hope I've got all the escaping right there.)
That's the C# escaped equivalent of the following JSON:
[{"answer":"Line 1","mark": 1}, {"answer":"Line 3","mark": 1}]
Then read up on JObject.Parse()for more info.
Yes it is json format. But There are multiple objects. You are not looping through it. One way could be
dynamic dynJson = JsonConvert.DeserializeObject(json);
foreach (var item in dynJson)
{
Console.WriteLine("{0} {1}\n", item.answer, item.mark);
}
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);