Newtonsoft JSON反序列化和jsonfreeze

时间:2013-11-10 14:19:35

标签: c# php json vb.net

我有两个简单的PHP类

class Order{
    public $orderNo;
    public $lines = array();
    public $paid = false;

    public function addLine(OrderLine $line) {
        $this->lines[] = $line;
    }

public function setPaid($paid = true) {
        $this->paid = true;
    }
}

class OrderLine{

public function __construct($item, $amount){
    $this->item = $item;
    $this->amount = $amount;
}

    public $item;
    public $amount;
    public $options;
}

序列化对象使用https://github.com/mindplay-dk/jsonfreeze

...

$json = new JsonSerializer;
$data = $json->serialize($order);

有输出:

{
  "#type": "Order",
  "orderNo": 123,
  "lines": [{
    "#type": "OrderLine",
    "item": "milk \"fuzz\"",
    "amount": 3,
    "options": null
  },{
    "#type": "OrderLine",
    "item": "cookies",
    "amount": 7,
    "options": {
      "#type": "#hash",
      "flavor": "chocolate",
      "weight": "1\/2 lb"
    }
  }],
  "paid": true
}

在VB.NET中发送字符串XMLRPC

使用Newtonsoft JSON获取实时对象?

以及如何通过类比生活VB.net或C#对象的json字符串来创建兼容格式?

2 个答案:

答案 0 :(得分:0)

这是你可以开始的东西。您创建了一些具有表示JSON格式的属性的类(未经测试的代码,就像想法一样):

public class MyData
{
    [JsonProperty("#type")]
    public string Type { get; set; }

    [JsonProperty("#orderNo")]
    public int OrderNo { get; set; 

    [JsonProperty("paid")]
    public bool Paid { get; set; }

    [JsonProperty("lines")]
    public List<MyDataLine> Lines { get; set; }
}

public class MyDataLines
{
    [JsonProperty("#type")]
    public string Type { get; set; }

    [JsonProperty("options")]
    public MyDataLinesOptions Options { get; set; }

    // ... more
}

public class MyDataLinesOptions
{
    // ... more
}

然后你可以像这样序列化和反序列化数据:

string json = "the json data you received";
MyData myData = JsonConvert.DeserializeObject<MyData>(json);

// ...

json = JsonConvert.SerializeObject(myData);

答案 1 :(得分:0)

“#type”:“订单”

“#type”:“OrderLine”,

这不是属性,这是对象类型的指示