6

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

gweilo
  • 63
  • 4

3 Answers3

4

Part of the issue looks to be the use of double quotes which can be escaped with a backslash \, however to have a multi-line string in C#, you also need to append an @ symbol at the start like shown in this answer https://stackoverflow.com/a/1100265/2603735

Community
  • 1
  • 1
Jayden Meyer
  • 703
  • 2
  • 18
  • 28
3

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.

Christoph
  • 2,211
  • 1
  • 16
  • 28
3

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: [] 
    }
}
}"
M.G.E
  • 371
  • 1
  • 10