Parsing JValue to either JObject or JArray - c#

Is there a nice way to get a json value, using var myValue = json["prop"] and insert it to a common object/interface? The value could be a json {} or an array []. I know I can insert them to a JObject and JArray, but is there a common object?
I also want to know (maybe the same answer to the above), if I can parse json from string, when again, I don't know if it's an array or an object.

The JToken type is a common base type for JObject and JArray. It is what json["prop"] would return, and if you had a JToken of either type, then you could set json["prop"] = token.

Related

How could I access to a Dictionary objects?

I have a dictionary parsed from a JSON (more information here Can't deserialize Dictionary from JSON) and finally could get the parse done. I get an object with this structure shown in the image. How can I access the values from this object curContent? The "natural" way was trying to cast curContent.soportes[0].avisos to Aviso[] but it says it cannot cast from jArray to Aviso[].
currContent.soportes[2].Value
but this will give you the json string it looks like. You'd need to deserialize that as well

Deserialize JSON Array with JSON.NET JArray

I'm trying to deserialize my JSON Array using Newtonsoft JSON.NET nugget:
Here's the code:
private List<TemplateTypesObj> getTemplateTypes(JArray array)
{
List<TemplateTypesObj> templateTypes = Newtonsoft.Json.JsonConvert.DeserializeObject<List<TemplateTypesObj>>(array);
return templateTypes;
}
The only issue is that DeserializeObject takes String, not an JArray object. I can do array.toString() but I'm not sure if that is a proper way to do that.
That's because a JArray doesn't really need deserializing. It's not a string/binary representation of an object (which is something you'd deserialize). It's already an object which represents your JSON. You can use it like an object - iterate through it, extract individual items from it.
Check out the docs at http://www.newtonsoft.com/json/help/html/t_newtonsoft_json_linq_jarray.htm - there are methods in there which I'm sure could be used to achieve the conversion you want.

NewtonSoft JsonConverter and the slash character

I am trying to create a dictionary from a Json array returned from a Web API which contains a file path value. I have extracted a sample here
JsonConvert.DeserializeObject<Dictionary<string, string>>("[{'Path':'\6\6553_20140729_134527059.mp3'}]")
Various combinations produce the following error. Only 1 approach works and I would love to know why. If someone can help.. much appreciated
Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'System.Collections.Generic.Dictionary`2[System.String,System.String]' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly.
To fix this error either change the JSON to a JSON object (e.g. {"name":"value"}) or change the deserialized type to an array or a type that implements a collection interface (e.g. ICollection, IList) like List<T> that can be deserialized from a JSON array. JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array.
Path '', line 1, position 1
The following throw the above error
//Escape with double slash
JsonConvert.DeserializeObject<Dictionary<string, string>>("[{'Path':'\\6\\6553_20140729_134527059.mp3'}]")
//Escape with quadruple slash
JsonConvert.DeserializeObject<Dictionary<string, string>>("[{'Path':'\\\\6\\\\6553_20140729_134527059.mp3'}]")
//Multiple Json Objects in array
JsonConvert.DeserializeObject<Dictionary<string, string>>("[{'Path':'\\6\\6553_20140729_134527059.mp3'},{'Path':'\\6\\6553_20140729_134527059.mp3'}]")
//Double slash, single Json object
JsonConvert.DeserializeObject<Dictionary<string, string>>("{'Path':'\\6\\6553_20140729_134527059.mp3'}")
This is the only thing that works
//Quadruple slash, single object
JsonConvert.DeserializeObject<Dictionary<string, string>>("{'Path':'\\\\6\\\\6553_20140729_134527059.mp3'}")
Like I said earlier, any help would be much appreciated
ALL THE TESTS DONE IN VISUAL STUDIO QUICK WATCH
When JSON starts with "[", it means that it represents List/Array, so the deserializer expect a List of some kind as parameter,
List<Dictionary<string, string>> in your case.

Serialize object to JToken

I have a a JObject and I would like to set a property from a strongly typed object on it.
JObject["ProductionVersion"] = new ProductionVersion();
In order to do this, ProductVersion needs to be converted to a JToken. How can I do this without having to serialize and deserialize the object as a JObject?
JObject["ProductVersion"] = JsonConvert.DeserializeObject<JObject>(JsonConvert.SerializeObject(message.ProductVersion))
Your question is a bit confusing..
So you have a JObject and you want a JToken?
Well, a JObject is a JToken. Take a look at the inheritance hierarchy here: JObject class
If what you meant is "I have a serializable object, and I want to convert it to a JToken without having to serialize and deserialize it again", then use this JToken.FromObject(obj)
You can access the properties by calling Properties on the JObject.
When you need to add a property, just add it using the JProperty constructor.
See the JSON.NET documentation.

JSON.NET exception when deserializing an array of GUIDs

I'm using JSON.NET to deserialize AJAX HTTP requests sent in from the browser, and am running into problems with web service calls that use a Guid[] as a parameter. This worked fine when I used the built in .NET serializer.
First off, the raw bytes in the stream look like this:
System.Text.Encoding.UTF8.GetString(rawBody);
"{\"recipeIds\":[\"d9ede305-d244-483b-a435-abcf350efdb2\"]}"
I then call:
Newtonsoft.Json.JsonSerializer serializer = new Newtonsoft.Json.JsonSerializer();
parameters[0] = serializer.Deserialize(sr, operation.Messages[0].Body.Parts[0].Type);
.Type is System.Guid[]
I then get the exception:
Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Guid[]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.
To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List<T>) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object.
Path 'recipeIds', line 1, position 13.
Web service methods that take in a single Guid (not an array) work, so I know JSON.NET is able to convert a string into a GUID, but it seems to blow up when you have an array of strings that you want to deserialize to an array of GUIDs.
Is this a JSON.NET bug, and is there a way to fix this? I suppose I could write my own custom Guid collection type, but I'd rather not.
You need a wrapper class
string json = "{\"recipeIds\":[\"d9ede305-d244-483b-a435-abcf350efdb2\"]}";
var obj = JsonConvert.DeserializeObject<Wrapper>(json);
public class Wrapper
{
public Guid[] recipeIds;
}
--EDIT--
Using Linq
var obj = (JObject)JsonConvert.DeserializeObject(json);
var guids = obj["recipeIds"].Children()
.Cast<JValue>()
.Select(x => Guid.Parse(x.ToString()))
.ToList();

Categories