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);
Related
I'm working with this Json structure, but I don't know how to get the values of the part of the "json" key
I'm using this code to send a request to an API, and the return is an Json object:
var reqData = (HttpWebRequest)WebRequest.Create(string.Format("http://server_ip/system/message/date/{0}/", txtDate.Text));
reqData.ContentType = "application/json";
reqData.Method = "GET";
var answer = (HttpWebResponse)reqData.GetResponse();
List<Dictionary<string, string>> convert = JsonConvert.DeserializeObject<List<Dictionary<string, string>>>(answer);
The result is a Json structure like this:
"[
{
\"idMessage\":\"--Message Id--",
\"idTemplate\":--TemplateId--,
\"mail\":\"--mail dir--\",
\"subject\":\"--message subject--\",
\"json\":\"{
\\\"Id\\\":\\\"--Person Id--\\\",
\\\"name\\\":\\\"--Person name--\\\",
\\\"date\\":\\\"--Register date-\\\",
\\\"hour\\\":\\\"--Register hour--\\\"
}\",
\"senddate\":\"--sent date--\",
\"status\":0,
\"template\":null
}
]"
I want to get the values (Id,name,date,hour) from the json part of this Json string, can someone help me to get this values?
That json property contains a string of more JSON, so you have to deserialize that again, the same way you did the whole outer structure.
So now that you have your convert array, you can pull out the first object, grab the value of json and deserialize that:
var json = JsonConvert.DeserializeObject<Dictionary<string, string>>(convert[0]["json"]);
Then you can pull each value out like this:
var id = json["Id"];
Mind you, the JSON in your question isn't actually valid. There are a few errors in it. But I'm assuming that they're just copy/paste errors and the web service is actually returning valid JSON.
I am sending a request to a WebAPI using following code:
client.PostAsync(baseAddress + path, new FormUrlEncodedContent(JsonConvert.DeserializeObject<Dictionary<string,string>>(form)))
where client is an object of HttpClient class. This code is executed for all the requests to the WebApi. I am trying to send following data to the API:
{
"code":"GUEST",
"category":"Indian",
"sections":["01000000-0000-0000-0000-000000000000","02000000-0000-0000-0000-000000000000"],
"date":"0001-01-01T00:00:00",
"time":"0001-01-01T00:00:00",
"quantity":1.0,
"price":0.0,
"discount":0.0,
"paymentMethod":"ID",
"paymentMethodID":null,
"ticketNo":null
}
Now because the FormUrlEncodedContent accepts only the Dictionary<string,string> object, I am converting this JSON into that type using NewtonSoft's JSON.NET method JsonConvert.DeserializeObject. But at the point where sections array starts, it is showing me this error message:
Unexpected character encountered while parsing value:[. Path 'sections'.
So, what approach should I follow if I want to use the same code for this kind of JSON data?
If you for any reason need to send all values as strings, then you must convert array of strings to string before deserializing it to Dictionary<string, string>.
It can be done like this:
var json = "{\"code\":\"GUEST\",\"category\":\"Indian\",\"sections\":[\"01000000-0000-0000-0000-000000000000\",\"02000000-0000-0000-0000-000000000000\"],\"date\":\"0001-01-01T00:00:00\",\"time\":\"0001-01-01T00:00:00\",\"quantity\":1.0,\"price\":0.0,\"discount\":0.0,\"paymentMethod\":\"ID\",\"paymentMethodID\":null,\"ticketNo\":null}";
var jObject = JObject.Parse(json);
jObject["sections"] = JsonConvert.SerializeObject(jObject["sections"].ToObject<string[]>());
var result = JsonConvert.DeserializeObject<Dictionary<string, string>>(jObject.ToString());
That way you will get result:
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);
I have a long string in JSON format. This is what it looks like:
{"ShowMapUrl":true,"GameDiffusionType":5,"InputYellowCards":false,"DisplayYellowCards":false,"InputYellowCards2":false}
Note that the string is much longer. I've been trying to convert that string into a dictionary by using json.NET without success. Any tips?
Use JsonConvert.DeserializeObject<Dictionary<string, object>>():
var json = #"{""ShowMapUrl"":true,""GameDiffusionType"":5,""InputYellowCards"":false,""DisplayYellowCards"":false,""InputYellowCards2"":false}";
var dict = JsonConvert.DeserializeObject<Dictionary<string, object>>(json);
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