0

I am passing JSON value from windows application to console application in args parameter, and trying to deserialize it in class object, but it is giving me error while doing it as below,

Unexpected character encountered while parsing value: L. Path 'Line1', line 1, position 8.

I am using JSON.NET library to do this. Below is my code,

Windows application,

Address address = new Address() { Line1 = "Line 1", Line2 = "Line 2" };
string json = JsonConvert.SerializeObject(address);
Process compiler = new Process();
compiler.StartInfo.FileName = @"D:\Learning\Console\ValidateAddress\ValidateAddress\bin\Debug\ValidateAddress.exe";
compiler.StartInfo.Arguments = json;
compiler.StartInfo.UseShellExecute = false;
compiler.StartInfo.RedirectStandardOutput = true;
compiler.Start();
compiler.WaitForExit();
button1.Text = compiler.StandardOutput.ReadToEnd();

Console application,

Address m = JsonConvert.DeserializeObject<Address>(args[0]);
System.IO.File.WriteAllText(@"D:\path.txt", args[0]);
Console.WriteLine(args[0]);

In console application, args[0] parameter is printing below value in text file,

{Line1:Line 1,Line2:Line 2}

In string values, it is not getting double quotes. (Line 1, instead of "Line 1")

In windows application, I am getting below string,

"{Line1:Line 1,Line2:Line 2}\r\n"

Where I need to do a change in console application during deserialisation to make it work?

Keval Patel
  • 925
  • 4
  • 24
  • 46

1 Answers1

0

The reason is that parameter passing to programs goes by its own rules.

In particular, quotes denote arguments that should not be split further, until the next quote ends the string. As such, the fact that you see the quotes being removed is both logical and expected.

You can quote the quotes but I don't know the exact syntax, perhaps a better answer comes along telling you how to escape the string before passing it as an argument.

A brief experiment indicates that you need to escape the double quotes by adding another double quote, and then encapsulating the entire json in a set of double quotes.

Example, this:

test.exe { "a": "b" }

Was received as 4 arguments:

  1. {
  2. a:
  3. b
  4. }

whereas this:

test.exe "{ ""a"": ""b"" } "

Was received as

  1. { "a": "b" }

I would not send json to the other program by way of arguments, I would either pipe it in as standard input, or provide it through a file.

Lasse V. Karlsen
  • 380,855
  • 102
  • 628
  • 825