Skip to content

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:

1. Follow the page below to use JSON.NET in your project.

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.

image

By looking into the meta value json string, you should see the data type should be List<Dictionary<string, string>>.

image

3. Define a MetaValueProcessor for V2 WCObject.

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;

4. Now, try to get the meta value again.

image

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.

image

6. You can even define a class for complicated meta value as below:

image

image

And use it in MetaValueProcessor:

image