1

Currently working on a Xamarin project, however facing an issue where object being serialized returns {}. May I have some advice on this?

Here's my entity class

public class TodoItem
    {
        [JsonProperty]
        public string ID { get; set; }

        [JsonProperty]
        public string Name { get; set; }

        [JsonProperty]
        public string Notes { get; set; }

        [JsonProperty]
        public bool Done { get; set; }

    }

The code where I serialize my object

public async Task SaveTodoItemAsync(TodoItem item, bool isNewItem = false)
        {
            //RestUrl = refer to constants.cs
            var uri = new Uri(string.Format(Constants.RestUrl, string.Empty));

            try
            {

                var json = JsonConvert.SerializeObject(item);
                var content = new StringContent(json, Encoding.UTF8, 
                "application/json");

               ...
            }
        }

Also, I have noticed when I try to insert data, they all lies in non-public members. Could that been the cause?

Sample

CodeName
  • 559
  • 2
  • 6
  • 23
  • 1
    You don't need to attribute your properties, they are automatically added. It is only needed if you want to call them something else when output or if you want to ignore the property. – Cheesebaron Apr 04 '18 at 17:32
  • @Cheesebaron I only added them when the serializing wasn't working. So even without the attributes, it doesn't work – CodeName Apr 04 '18 at 17:34
  • are you sure your item is not null? – Jason Apr 04 '18 at 17:54
  • @Jason I traced, the content variable is null, but the json variable is {} – CodeName Apr 04 '18 at 18:13
  • 1
    no, I mean does the item that you are serializing have values in its properties? – Jason Apr 04 '18 at 18:41
  • @Jason Yes, they have values in them. But they're under non-public members. – CodeName Apr 04 '18 at 18:47
  • What do you mean? The TodoItem class you posted ONLY has 4 public properties, nothing else. – Jason Apr 04 '18 at 19:03
  • @Jason I have a UI page which will insert the values into them. – CodeName Apr 05 '18 at 02:47
  • Are you using the Xamarin Live Player app? If so this is a duplicate of [JsonConvert.SerializeObject always return {} in XamarinForms](https://stackoverflow.com/q/48041823/3744182) and [Newtonsoft.JSON serializeobject returns empty JSON string](https://stackoverflow.com/q/48914561/3744182). See also https://learn.microsoft.com/en-us/xamarin/tools/live-player/limitations?tabs=android which indicates there is *Limited support for reflection (currently affects some popular NuGets, like SQLite and Json.NET).*. – dbc Apr 05 '18 at 05:19
  • @dbc Didn't manage to find these articles, read them and it's exactly the problem I am facing. Thank you – CodeName Apr 05 '18 at 10:11

0 Answers0