0

我有两个简单的 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 OR C#对象的json字符串来创建兼容的格式?

4

2 回答 2

0

"#type": "订单"

"#type": "OrderLine",

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

于 2013-11-11T05:49:46.833 回答
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);
于 2013-11-10T18:44:15.210 回答