Json.DeserializeObject Always Null

IndraIndra USMember ✭✭
edited April 2018 in Xamarin.Forms

Hi Everybody,Could i ask for some help ?
I write the code but why everytime i used Json.DeserializeObject always got null value ?
I check null value with DisplayAlert but if content from readasstringasync not null

Thank You

protected async void OnGetList()
{
try
{
using (var cl = new HttpClient())
{
var formcontent = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string,string>("key","getallimage")
//new KeyValuePair<string, string>("password","shah")
});
var request = await cl.PostAsync(Url, formcontent);

                request.EnsureSuccessStatusCode();
                var content = await request.Content.ReadAsStringAsync();
                
                //Activity indicator visibility on
                activity_indicator.IsRunning = true;

                var tr = JsonConvert.DeserializeObject<BarangCs>(content);
                //Getting JSON data from the Web
                //var content = await _client.GetStringAsync(Url);
                //We deserialize the JSON data from this line
                //After deserializing , we store our data in the List called ObservableCollection

                ObservableCollection<Resultbarang> trends = new ObservableCollection<Resultbarang>(tr.resultbarang);
                DisplayAlert("O", trends[0].nama, "Ok");
                //Then finally we attach the List to the ListView. Seems Simple :)
                myList.ItemsSource = trends;


                //We check the number of Items in the Observable Collection
                int i = trends.Count;
                if (i > 0)
                {
                    //If they are greater than Zero we stop the activity indicator
                    activity_indicator.IsRunning = false;
                }

                //Here we Wrap  the size of the ListView according to the number of Items which have been retrieved 
                i = (trends.Count * heightRowsList);
                activity_indicator.HeightRequest = i;
            }
        }
        catch (Exception ey)
        {
            Debug.WriteLine("" + ey);
        }


    }

Posts

  • JoeMankeJoeManke USMember ✭✭✭✭✭
    1. What do the class definitions for BarangC and Resultbarang look like?
    2. What is the value of content?
    3. Are you getting an exception? If so, what is the exception?
    4. Learn MVVM. Please.
  • ChrisColeTechChrisColeTech USMember ✭✭✭
    edited April 2018

    @JoeManke said:
    1. What do the class definitions for BarangC and Resultbarang look like?
    2. What is the value of content?
    3. Are you getting an exception? If so, what is the exception?
    4. Learn MVVM. Please.

    Lol the answer to #3 is probably "Object reference not set to an instance of an object"

    But, I would also like to know the answer to #1 and #2...because if it can't deserialize then there must be something wrong with the BarangCs class it is trying to convert to.

    there could be a property on the BarangCs object that is not being populated in your Http response, and when you check it - it is null. I'm very interested in the BarangCs file now

  • IndraIndra USMember ✭✭

    This is my Barangcs class :

    public class Resultbarang
    {
    public string idbarang { get; set; }
    public string nama { get; set; }
    public string merek { get; set; }
    public string harga { get; set; }
    public string hargaonline { get; set; }
    public string stocketalase { get; set; }
    public string stockgudang { get; set; }
    public string berat { get; set; }
    public string reminder { get; set; }
    public string barcode { get; set; }
    public string kategori { get; set; }
    public string satuan { get; set; }
    public string referensihitung { get; set; }
    public string catatan { get; set; }
    public string minimalorder { get; set; }
    }

    public class BarangCs
    {
        public List<Resultbarang> resultbarang { get; set; }
    }
    

    @JoeManke @ChrisColeTech
    I got no error in my xamarin that's why i confused about the error

    @JoeManke
    Thank You for your Advice, I will learn about that :smiley:

    How can i check if object null or not ?

    Thank You @JoeManke @ChrisColeTech

  • ChrisColeTechChrisColeTech USMember ✭✭✭
    edited April 2018

    @Indra said:
    How can i check if object null or not ?

    try

    if (object != null){
    }
    

    and you have a try/catch statement. try setting a breakpoint in the catch statement while debugging.

  • IndraIndra USMember ✭✭

    @ChrisColeTech Still the same,my object not null but not show anything

    {"resultbarang":[{"idbarang":"0000001","nama":"Coba","merek":"Coba","harga":"45000","hargaonline":"45000","stocketalase":"12","stockgudang":"12","berat":"800","reminder":"12","barcode":"0000001","kategori":"Makanan","satuan":"Gram","referensihitung":"300","catatan":"Empty","minimalorder":"2"}]}

    Is There anything wrong with my json ?

    Thank You

  • ChrisColeTechChrisColeTech USMember ✭✭✭

    the JSON is ok, but your c# class should look like this:

    public class BarangCs
    {
        public Resultbarang[] resultbarang { get; set; }
    }
    
    public class Resultbarang
    {
        public string idbarang { get; set; }
        public string nama { get; set; }
        public string merek { get; set; }
        public string harga { get; set; }
        public string hargaonline { get; set; }
        public string stocketalase { get; set; }
        public string stockgudang { get; set; }
        public string berat { get; set; }
        public string reminder { get; set; }
        public string barcode { get; set; }
        public string kategori { get; set; }
        public string satuan { get; set; }
        public string referensihitung { get; set; }
        public string catatan { get; set; }
        public string minimalorder { get; set; }
    }
    
  • IndraIndra USMember ✭✭

    @ChrisColeTech still same sir,not showing anything but with no error :(
    Any suggest to fix this weird error ?

    Thank You

  • Gigex42Gigex42 USMember ✭✭✭✭

    When using this site you can check if your json is correct.

    And you Barangcs class is the same in you webservice and your app?

  • IndraIndra USMember ✭✭

    @Gigex42 I am already use that site Sir,but still not show anything...I generate my class from that site.
    Any Solution for this error ?

    Thank You for your help :smile:

  • Gigex42Gigex42 USMember ✭✭✭✭

    Just tested this on my project. Works fine. Copied your class and tried deserializing the string you posted.

    So when hitting a breakpoint on

      var tr = JsonConvert.DeserializeObject<BarangCs>(content);
    

    and go one step further tr is null correct?

  • IndraIndra USMember ✭✭

    @Gigex42 Yes,that's correctly. I alwasy get null after this

    var tr = JsonConvert.DeserializeObject(content);

    Do you know the problem ? or maybe i am missing some step ?

    Thank You for try my code :)

  • SzbestaSzbesta Member ✭✭✭
    edited April 2018

    @Indra Just try to deserialize to List<ResultBarang> then construct your barangcs class from that. Had a similar problem with JsonDeserializeObject this fixed it for me. Had a similar class structure as you!

  • IndraIndra USMember ✭✭
    edited April 2018

    @Szbesta The Result still same Sir.
    I check it with displayalert and still got null value.

    Is there any other way to deserialize object ?

    Thank You

  • SzbestaSzbesta Member ✭✭✭

    Hm are you testing using an emulator, over USB or on the Xamarin Live Player. If you are testing on the Live Player it has some issues with some Library if no then I'm afraid I'm out of options :/

  • IndraIndra USMember ✭✭

    @Szbesta I am testing with my galaxy note 5 with API 24
    Is that any problem with API 24 ?
    My pc running slowly if i use emulator :smile:

    It's Ok,Thank you for your help Sir

  • SzbestaSzbesta Member ✭✭✭

    Now that shouldn't be a problem. I myself am testing on a device with API 24. I'll try out your code and will tell you the outcome shortly!

  • IndraIndra USMember ✭✭

    @Szbesta Thank You Very Much Sir
    Sorry for the trouble :blush:

  • SzbestaSzbesta Member ✭✭✭

    No problem at all thats what the forums are here for to get some help ! :D

  • SzbestaSzbesta Member ✭✭✭
    edited April 2018

    @Indra
    Just threw together a quick test app to test your code. I got it working out of the box so there must be a minor issue here we are all overlooking.
    The classes i use are exactly the same as yours namely:
    public class BarangCS { public ResultBarang[] resultbarang { get; set; } }
    And:

    public class ResultBarang { public string idbarang { get; set; } public string nama { get; set; } public string merek { get; set; } public string harga { get; set; } public string hargaonline { get; set; } public string stocketalase { get; set; } public string stockgudang { get; set; } public string berat { get; set; } public string reminder { get; set; } public string barcode { get; set; } public string kategori { get; set; } public string satuan { get; set; } public string referensihitung { get; set; } public string catatan { get; set; } public string minimalorder { get; set; } }
    Now the interesting bit the deserialization and null checking:
    Deserialization:
    String json = r.ReadToEnd(); var ret = JsonConvert.DeserializeObject<BarangCS>(json); return ret;
    I'm reading out of a file the content of the json file is the JSON you posted before so no differences there

    Null Checking in the app:
    BarangCS dis = DataManager.Deserialize(); if (dis != null) { DisplayAlert("Object", dis.resultbarang[0].barcode, "OK"); }~~~~
    The DataManager Class just executes the code above

    Hope this will help you kind of :smile:

    Edit:Code Formatting kinda screwing around sorry for that :D

  • IndraIndra USMember ✭✭
    edited April 2018

    @Szbesta It's Ok,Thank you very much for your help :blush:
    I want to ask something about Deserialize(), Is that you use JavaScriptSerializer from nuget ?
    Sorry,i am a little confused :smiley:

  • SzbestaSzbesta Member ✭✭✭

    @Indra
    No the DataManager.Deserialize() is a Method i wrote myself the content of this Method is in the above post. To deserialize the JSON itself I'm using the Newtonsoft.Json Library.

  • IndraIndra USMember ✭✭

    @Szbesta Oh,i see. i am already try it just now but Still Empty
    I don't know what is wrong :neutral:

    Thank You for your help

  • IndraIndra USMember ✭✭

    @Szbesta @Gigex42 @ChrisColeTech @JoeManke
    Thank You Very Much Everyone.
    I am already found the problem :smiley:
    Error not from my code but from my device

  • ChrisColeTechChrisColeTech USMember ✭✭✭
    edited April 2018

    @Indra said:
    Thank You Very Much Everyone.
    I am already found the problem :smiley:
    Error not from my code but from my device

    Thats fantastic.

    I'm happy you were able to find the problem, and hopefully a solution.

    best regards,

    chris

  • SzbestaSzbesta Member ✭✭✭

    @Indra
    Nice to hear you figured out the problem!

    Thank You Very Much Everyone.

    No Problem mate thats what the forums are here for!

Sign In or Register to comment.