I have got an issue like
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.
My json file
{age : 20}
userinfo.cs
[System.Serializable]
public class UserInfo
{
public string age ;
[Newtonsoft.Json.JsonConstructor]
public UserInfo(string _age )
{
age = _age ;
}}
main.cs
public List<UserInfo>userInfoListw
userInfoListw = JsonConvert.DeserializeObject<List<UserInfo>>(Resources.Load<TextAsset>("User").ToString());
I know one of solution could be [{age : 20}],
but I do not really want to put [] into my Json file,
Please let me know another way to solve it.
I know one of solution could be [ {age : 20}], but I do not really want to put [] into my Json file, Please let me know anther way to solve it
Well, you're deserializing the JSON data into a List object. But your JSON data is not actually a List.
{age : 20}
If you deserialize it as a List, then Newtonsoft's library is going to expect a collection in the JSON (array brackets, like you pointed out). So either it's a List, or it isn't. You can either make it a collection with a single element -- which requires you to wrap the JSON in brackets, which you stated you don't want to do -- or you can change your code so it does not deserialize it into a List:
public UserInfo userInfow
userInfow = JsonConvert.DeserializeObject<UserInfo>(Resources.Load<TextAsset>("User").ToString());
Related
This question already has answers here:
How to deserialize an array of values with a fixed schema to a strongly typed data class?
(3 answers)
Closed 6 months ago.
I want to parse json into an object, problem is I don't have the key names in the json, only the values. Is it possible to parse these values into an object?
Code example:
public class Test
{
public uint one;
public bool trueOrFalse;
public uint three;
}
private void ParseTest()
{
Test test = JsonConvert.DeserializeObject<Test>("[1, true, 3]");
}
Error I get using Newtonsoft.Json:
JsonSerializationException: Cannot deserialize the current JSON array (e.g. [1,true,3]) into type 'Test' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly.
Edit:
What I want is to unfold the array onto an object's properties, in declaration order.
I work with a project where I get a lot of these value arrays and I cannot write a custom convert function for all of them.
My first solution was a function that would insert the field names into the json before parsing, but this eventually broke when the json structure became more complicated (class in a class...).
your json is array, but you are trying to deserialize object. This code will work for you
var json="[1, true, 3]";
var jsonArray=JArray.Parse(json.Dump()).ToArray();
or if you want to convert to c# class
Test test = new Test
{
one= (uint)jsonArray[0],
trueOrFalse= (bool)jsonArray[1]
three= (uint)jsonArray[2],
}
this json will work for your class
var json = "{\"one\":1, \"trueOrFalse\":true, \"three\": 3}";
Test test = JsonConvert.DeserializeObject<Test>(json);
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.
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.
I am having some trouble getting an array of objects in C# to serialize to JSON.
My Code:
friendlyNotification[] notifications = ns.friendlyNotifications.ToArray();
string json = JsonConvert.SerializeObject(notifications);
return Json(json, JsonRequestBehavior.AllowGet);
The code above return the following:
[{}]
Does anyone have and idea why this isn't working? Something to do with the fact that I am trying to serialize an array?
Thanks.
As friendlyNotification is a class without public properties, and notifications contains only one element the json result is [{}].
The json [{}] has the meaning, of an array with an empty object.
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();