2012-08-16 60 views
2

什么是创建一个可序列化作为一个C#类的最佳方式:系列化C#对象JSON

marks:   [ 
      { c: [57.162499, 65.54718], // latitude, longitude - this type of coordinates works only for World Map 
       tooltip: 'Tyumen - Click to go to http://yahoo.com', // text for tooltip 
       attrs: { 
         href: 'http://yahoo.com',   // link 
         src: '/markers/pin1_red.png'  // image for marker 
         } 
      }, 
      { xy: [50, 120], // x-y coodinates - works for all maps, including World Map 
       tooltip: 'This is London! Click to go to http://london.com', 
       attrs: { 
         href: 'http://yahoo.com',   // link 
         src: '/markers/pin1_yellow.png'  // image for marker 
         } 
      } 
      ] 

在上面的代码中我们分配或者分配“C”或“XY”,但不能两者都同一时间。 我正在使用Newtonsoft.Json。 我唯一想要的是可以序列化到上面的代码的C#类。

+0

你想有两个属性或两个类的类? – 2012-08-16 13:03:03

+0

@WouterdeKort:实际上是一个4类属性{c,xy,tooltip,attrs}。 – 2012-08-16 13:27:46

回答

4

类看起来是这样的:

[Serializable] 
public class Marks 
{ 
    public List<latlon> marks = new List<latlon>(); 
} 

public class latlon 
{ 
    public double[] c; 
    public int[] xy; 
    public string tooltip; 
    public attributes attrs; 

    public latlon (double lat, double lon) 
    { 
     c = new double[] { lat, lon }; 
    } 
    public latlon (int x, int y) 
    { 
     xy = new int[] { x, y }; 
    } 
} 

public class attributes 
{ 
    public string href; 
    public string src; 
} 

的代码来测试它看起来像这样:

string json; 

Marks obj = new Marks(); 
latlon mark = new latlon(57.162, 65.547) 
    { 
     tooltip = "Tyumen - Click to go to http://yahoo.com", 
     attrs = new attributes() 
     { 
      href = "http://yahoo.com", 
      src = "/markers/pin1_red.png" 
     } 
    }; 

obj.marks.Add(mark); 

mark = new latlon(50, 120) 
    { 
     tooltip = "This is London! Click to go to http://london.com", 
     attrs = new attributes() 
     { 
      href = "http://yahoo.com", 
      src = "/markers/pin1_yellow.png" 
     } 
    }; 

obj.marks.Add(mark); 

//serialize to JSON, ignoring null elements 
json = JsonConvert.SerializeObject(obj, Formatting.None, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });