I have a JSON string returned from API that sometimes like this, in which the "result"
key only has an empty object :
{
"_meta": {
"status": "SUCCESS",
"count": 0
},
"result": {}
}
or this, in which the "result"
key has an array of object:
{
"_meta": {
"status": "SUCCESS",
"count": 0
},
"result": [
{ ... },
{ ... }
]
}
I've tried implementing custom JsonConverter
from this question, but I guess I got no luck. Here is my implementation:
class EmptyObjectJsonConverter<T> : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return true;
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
object retObj = new Object();
if (reader.TokenType == JsonToken.StartArray)
{
retObj = serializer.Deserialize<List<T>>(reader);
}
else if (reader.TokenType == JsonToken.StartObject)
{
retObj = new List<T>();
}
return retObj;
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotImplementedException();
}
}
And I use it this way:
public class ApiReturn
{
public ApiMeta _Meta { get; set; }
[JsonConverter(typeof(EmptyObjectJsonConverter<ApiResult>))]
public List<ApiResult> Result { get; set; }
}
What I want to achieve from above implementation is: if the token is start array, then deserialize it in a normal way, but if the token is start object, then just return an empty list of object.
But then, when I tried running the program with the "result"
key having an empty object, it throws exception: Additional text found in JSON string after finishing deserializing object.
, and the resulting ApiReturn.Result
is null.
Did I implement it in a wrong way? Any help would be appreciated.
UPDATE based on @A. Chiesa answer: Please look at my implementation of GetApiResult
:
[JsonProperty("result")]
public JToken Result { get; set; }
public T GetResultAs<T>()
{
var objectReturned = default(T);
try
{
if (Result.Type == JTokenType.Array)
{
objectReturned = Result.ToObject<T>();
}
else if (Result.Type == JTokenType.Object)
{
// Should it return an empty List<ApiResult> if I use type List<ApiResult> ?
objectReturned = default(T);
}
}
catch
{
objectReturned = default(T);
}
return objectReturned;
}
Why I get null when the JSON node token is object? Should it return an empty List<ApiResult>
when I use GetResultAs<List<ApiResult>>
?
>()` is null.
– Rizki Pratama Mar 08 '17 at 07:50