1

i created a json file on my server which im using to send data to a c# program through JSON.NET deserialize. However im im getting a null object exception, can anyone please show me how to create the classes. Thanks My class is here

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Newtonsoft.Json;

namespace WindowsFormsApplication4
{
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        Load();
    }
    public void Load()
    {
        label1.Text = "State:\nLoading...";
        try
        {
            Products pd = new Products();
            using (var webClient = new System.Net.WebClient())
            {
                // download json from url
                var json = webClient.DownloadString(url);
                // Now parse with JSON.Net
                Products convert = JsonConvert.DeserializeObject<Products>(json) as Products;
                label1.Text += pd.info.ToString();
                label1.Text += "\nWeb Service Connected To";
            }
        }
        catch (JsonSerializationException jsonerr) { label1.Text += "\nWeb Service Connection Failed"; MessageBox.Show(jsonerr.ToString()); }
        catch (Exception err) { throw; }
        finally { label1.Text += "\nWeb Service Closed"; }
    }
}

}

public class Products
{
    public Info info;

    [JsonProperty("post")]
    public Info infos
    {
        get { return info; }
        set { info = value; }
    }
}

public class Info
{
    private string pd_name;
    private int pd_id;

    [JsonProperty("pd_id")]
    public int pd_ids
    {
        get { return pd_id; }
        set { pd_id = value; }
    }

    [JsonProperty("pd_name")]
    public string pd_names
    {
        get { return pd_name; }
        set { pd_name = value; }
    }
}

1 Answer 1

1

You're not handling the posts value in the JSON. So if your JSON is formatted like this:

{ "posts" : [ { "post" : { "pd_id" : "399", 
                           "pd_name" : "1.2mm  Cylinder Labret"} },
              { "post" : { "pd_id" : "415", 
                           "pd_name" : "1.2mm  Laser Etched Labret" }}
            ] }

Try setting up your classes like this:

public class Posts
{
    public List<Products> posts { get; set; }
}

public class Products
{
    public List<Info> post { get; set; }
}

public class Info
{
    public string pd_id { get; set; }
    public string pd_name {get; set; }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.