Reputation: 1020
I have JSON string results as follows.
In this response Sometimes sizeKey and sizeName properties are returned as a string. But sometimes both properties are returns inside an array as follows
I am using following code to convert it to object
var assets = jObject["assets"].Children().ToList();
foreach (var item in assets)
{
decorationAssets.Add(item.ToObject<AEDecorationAssets>());
}
And my AEDecorationAssets class is as follows.
public class AEDecorationAssets
{
public string Id { get; set; }
public string Url { get; set; }
public string[] Colors { get; set; }
public string FontKey { get; set; }
public string SizeKey { get; set; }
public string ViewKey { get; set; }
public string FontName { get; set; }
public int Rotation { get; set; }
public string SizeName { get; set; }
public string TextValue { get; set; }
public string EntityType { get; set; }
public string LocationCode { get; set; }
public string LocationName { get; set; }
public string TextEffectKey { get; set; }
public string TextEffectName { get; set; }
public string DecorationMethod { get; set; }
public string NumDecorationColors { get; set; }
}
At the time when "sizeKey" is an array, the above code gives an error. How can I resolve this issue? Is there any JSON property we can use to resolve it?
Upvotes: 0
Views: 667
Reputation: 17
Simply get json result for which you want to create c# object and then you can valid json response from https://jsonlint.com/ and then you can create c# object of any type json response which you want through http://json2csharp.com. And after get c# object of your json response you only need to deserialization of your json response to c# object which you have created. which will return you expected result.
Upvotes: 0
Reputation: 3459
If a JSON type is sometime an array
, and sometimes a string
, you can't really map it simply to a .NET type, as there is none that supports this behavior.
So first you need a datatype that can store this, like and string[]
or List<string>
.
It could be that JsonConvert
will solve this automatically, but otherwise you'll need to write a custom ContractResolver
or JsonConverter
. Here you can detect if the source property is a string or array. If it's an array
, you can use the default deserialization. If it is a string
, you need to convert it to an array with a single value.
Upvotes: 0
Reputation: 3653
One way you can do it is by making your SizeKey
type an object
(i.e. public object SizeKey { get; set; }
), then you can switch/case on item.ToObject<AEDecorationAssets>().SizeKey.GetType()
to figure out how to handle it (i.e. if String
do this, if JArray
do that), etc.
Upvotes: 3