简体   繁体   中英

How to turn plain text json data into string?

I am trying to mock up some test data to check wether a json string deserializes into an object correctly.

I have some json data which is 660 lines long, so i have only included a portion

{
"DataA": "string",
"DataB": "datetime",
"DataC": {
    "DataC1": "datetime",
    "DataC2": "datetime",
    "DataC3": "datetime",
    "DataC4": int,
    "DataC5": int,
    "DataC6": "string",
    "DataC7": int,
    "DataC8": "object"
},
"DataD": {
    "DataD1": decimal,
    "DataD2": decimal,
    "DataD3": "string",
    "DataD4": int,
    "DataD5": decimal,
    "DataD6": "string",
    "DataD7": {
        "DataD7i": null,
        "DataD7ii": [

I have created the corresponding classes, but am currently attempting to test them. However I am unable to get this json data into a string, as the double quotation marks close off the string. I have tried using ecsapes aswell but to no avail.

string testjson = "{
"DataA": "string",
"DataB": "datetime",
"DataC": {
    "DataC1": "datetime",
    "DataC2": "datetime",
    "DataC3": "datetime",
    "DataC4": int,
    "DataC5": int,
    "DataC6": "string",
    "DataC7": int,
    "DataC8": "object"
},
"DataD": {
    "DataD1": decimal,
    "DataD2": decimal,
    "DataD3": "string",
    "DataD4": int,
    "DataD5": decimal,
    "DataD6": "string",
    "DataD7": {
        "DataD7i": null,
        "DataD7ii": ["

I want to call

            ObjectA objectblah= JsonConvert.DeserializeObject<ObjectA>(output);

But cannot manage to get the json into a string. I am aware this is a trivial issue, but I am new and am stuck on this issue. any help would be greatly appreciated.

Thanks

问题的一部分看起来是使用双引号,可以使用反斜杠\\来转义,但是要在C#中使用多行字符串,您还需要在开头添加@符号,如此答案https中所示: //stackoverflow.com/a/1100265/2603735

In my unit test projects, whenever I have "mass" text, I put that content into a separate text file. Then you have two choices:

  1. Make that text file an embedded resource, which you can load via Assembly.GetExecutingAssembly().GetManifestResourceStream(...).
  2. Or set the file's project property "Copy to output directory" to "If newer". Then just read it via File.ReadAllText.

Keeping it in a separate file makes editing/maintenance a lot easier.

Use it like this:

  string testjson = @"
{
DataA: string,
DataB: datetime,
DataC: {
    DataC1: datetime,
    DataC2: datetime,
    DataC3: datetime,
    DataC4: int,
    DataC5: int,
    DataC6: string,
    DataC7: int,
    DataC8: object
},
DataD: {
    DataD1: decimal,
    DataD2: decimal,
    DataD3: string,
    DataD4: int,
    DataD5: decimal,
    DataD6: string,
    DataD7: {
        DataD7i: null,
        DataD7ii: [] 
    }
}
}"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM