C#Newtonsoft.Json转换类型

时间:2016-10-25 11:12:48

标签: c# json types

我必须: DeserializeObject - 做一些更改 - SerializeObject 当我的Json有多种类型时,例如

{
  "type": "test",
  "currentStatus": "Active",
  "id": "987",
  "items": [
    {
      "type": "test1",
      "id": "123",
      "name": "Segment Members",
      "memberCount": "0",
      "outputTerminals": [
        {
          "type": "test2",
          "id": "123",
          "connectedId": "123",
          "terminalType": "out"
        }
      ],
      "position": {
        "type": "Position",
        "x": "46",
        "y": "14"
      },
      "isFinished": "true",
      "isRecurring": "false",
      "segmentId": "123"
    },
    {
      "type": "test5",
      "id": "1390",
      "name": "Yay! Clickers",
      "memberCount": "2",
      "position": {
        "type": "Position",
        "x": "330",
        "y": "375"
      },
      "waitFor": "2592000"
    },
    {
      "type": "test3",
      "id": "1391",
      "name": "test",
      "memberCount": "73",
      "outputTerminals": [
        {
          "type": "test4",
          "id": "123",
          "connectedId": "123",
          "connectedType": "CampaignWaitAction",
          "terminalType": "yes"
        },
        {
          "type": "test4",
          "id": "123",
          "connectedId": "123",
          "connectedType": "CampaignWaitAction",
          "terminalType": "no"
        }
      ],
      "position": {
        "type": "Position",
        "x": "123",
        "y": "123"
      },
      "testId": "123"
    }
  ]
}

我应该使用哪种数据类型进行此操作?动态,对象,Jobject ......?或者别的什么?

3 个答案:

答案 0 :(得分:3)

我只想创建一个对象并将其解除个性化。比动态动作容易得多。 (假设它总是留在那个结构中)

该怎么做

复制你的Json:

 `Edit` -> `Paste Special` -> `Paste JSON As CLASSES` 

你去吧!您有要反序列化的类型。

var deserializedJson = JsonConvert.DeserializeObject<YourNewObject>(jsonString);

注意:如果json类的粘贴不起作用,请确保您的json有效:ClickHereToValidateJson

答案 1 :(得分:1)

您可以创建类并序列化/反序列化json:

string json = JsonConvert.SerializeObject(rootObject);
Root root = JsonConvert.DeserializeObject<Root>(json);

然后:

string json = JsonConvert.SerializeObject(dynamicObject);
dynamic obj = JsonConvert.DeserializeObject(json);

此外,您可以使用不带类的动态类型:

Traceback (most recent call last):
  File "E:\test_runners 2 edit project\selenium_regression_test_5_1_1\Regression_TestCase\RegressionProjectEdit_TestCase.py", line 2714, in test_000057_run_clean_and_match_process
    process_lists_page.wait_for_run_process_to_finish()
  File "E:\test_runners 2 edit project\selenium_regression_test_5_1_1\Pages\operations.py", line 334, in wait_for_run_process_to_finish
    EC.text_to_be_present_in_element("No data to display"))
TypeError: __init__() takes exactly 3 arguments (2 given)

答案 2 :(得分:1)

using Newtonsoft.Json;          
dynamic collection = new
{
  MultipleType = //call function which returns json here
};
//serialize
var jsonSerializedFeed = JsonConvert.SerializeObject(MultipleType);
//deserialize
var jsonSerializedFeed = JsonConvert.DeserializeObject(MultipleType);

希望有所帮助