2013-05-18 4 views
1

JSON.NET을 통해 C# 프로그램에 데이터를 보내는 데 사용하는 내 서버에 json 파일을 만들었습니다. 그러나 메신저 null 개체 예외를 받고, 아무도 날 클래스를 만드는 방법을 보여주십시오 수 있습니다. 덕분에 내 클래스} 여기json.net 클래스를 비 직렬화

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

당신은 JSON에서 posts 값을 처리하지 않을 것입니다. 그래서 JSON은 다음과 같이 포맷 된 경우 :

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

이 같은 클래스를 설정하십시오 :

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; } 
} 
관련 문제