Search code examples
c#jsonparsinguwpjson-deserialization

Deserialize my JSOn and bind to list in C# UWP


My Service returns a JSON like below, I want to Parse this and bind category_name to my list, how to do this in C#, UWP apps.

Iam trying to Deserialize this in this way

var content_resp = await response.Content.ReadAsStringAsync();

            content_resp = "{ \"root\": " + content_resp.Trim().TrimStart('{').TrimEnd('}') + " }";
            var xmlProducts = JsonConvert.DeserializeXNode(content_resp);

            var xmlProductNodes = xmlProducts.DescendantNodes();

            foreach (XElement xmlProduct in xmlProductNodes)
            {
                Places pl = new Places();
                var node = xmlProducts.Element("category_parent").Value;

                    pl.category_name = xmlProducts.Element("category_name").Value;                                                         
            }                
        }
        catch (Exception ex)
        {
            //throw or return an appropriate response/exception
        }

when the debuger comes at this line

var xmlProducts = JsonConvert.DeserializeXNode(content_resp);

it is giving an error like "This operation would create an incorrectly structured document."


Solution

  • The easiest way that I have found is to use Newtonsoft.Json
    Firstly you should create class with data equal to your JSON:

    public class AppsData
    {
        private string _category_id;
        private string _category_name;
    
        public string category_id
        {
            get { return _category_id; }
            set { _category_id = value; }
        }
    
        public string category_name
        {
            get { return _category_name; }
            set { _category_name = value; }
        }
    }
    

    Then you can create some helper class:

        static class JSONhelper
    {
    
        public static IList<T> DeserializeToList<T>(string jsonString)
        {
            var array = Newtonsoft.Json.Linq.JArray.Parse(jsonString);
    
            IList<T> objectsList = new List<T>();
    
            foreach (var item in array)
            {
                try
                {
                    objectsList.Add(item.ToObject<T>());       
                }
                catch { }    
            }
            return objectsList;
        }
    }
    

    Then create instance of List

    IList<AppsData> appsdata;
    

    and try to deserialize:

     appsdata = JSONhelper.DeserializeToList<AppsData>(stringWithJSON);