-
-
Notifications
You must be signed in to change notification settings - Fork 219
Handle different types of Meta Value in WC Restful API V2
James Yang edited this page May 20, 2017
·
2 revisions
As you know, in WooCommerce Restful API V2, meta value can be in many different types, string, List or others, It's very difficult to deserialize the json string into a correct object with all information, currently in WooCommerce.NET, all meta value type is default to object.
The following steps will show your how to deserialize meta value in correct object:
How to use JSON.NET in WooCommerce.NET
2. Now try to deserialize a json string with customized meta value type, you can see it will be deserialize into a JObject or JArray. It's difficult to get the information we want.
By looking into the meta value json string, you should see the data type should be List<Dictionary<string, string>>.
object ProcessMetaValue(string parentTypeName, object value)
{
if (value != null && value.GetType().FullName.StartsWith("Newtonsoft.Json"))
{
if (value.GetType().FullName.EndsWith("JArray"))
{
JArray ja = (JArray)Convert.ChangeType(value, typeof(JArray));
if (ja.HasValues)
{
try
{
return ja.ToObject<List<Dictionary<string, string>>>();
}
catch { }
return value;
}
else
return null;
}
else if (value.GetType().FullName.EndsWith("JObject"))
{
JObject jo = (JObject)Convert.ChangeType(value, typeof(JObject));
if (jo.HasValues)
{
return jo.ToObject<ComplicatedMeta>();
}
else
return null;
}
else
return value;
}
else
return value;
}
WCObject.MetaValueProcessor = ProcessMetaValue;
You can see the meta value has been deserialized into a correct data type, with all information.
5. In MetaValueProcessor, you can use the parentTypeName to check which object are the meta values come from, Product, Coupon or Order.
And use it in MetaValueProcessor: