0

I am trying to send a JSON string into Azure IoT Hub with the following format:

string format = "{\"info1\":\"info1Data\",\"info2\":\"info2Data\",\"info3\":{\"info3Data\":[]}}";

The problem is that after I serialize the string into a JSON Object it sends this to the IoT Hub :

{\"info1\":\"info1Data\",\"info2\":\"info2Data\",\"info3\":{\"info3Data\":[]}}

My goal is to remove the '\' character from the string sent to the IoT, and with that goal i tried several ways to work around this problem , such as :

 var test= new string(format.ToCharArray());
 test.Trim();
 Console.WriteLine(test);
 testing = test.Replace(@"\", "");
 Console.WriteLine(testing);

OR

var charsToRemove = new string[] { @"\" };
 foreach (var c in charsToRemove)
 {
    testing = testing.Replace(c, string.Empty);
 }
 Console.WriteLine(testing);

I'm using VS2019 and I still can't remove the '\' char from the string.

Thanks in advance.

Lopes
  • 45
  • 6

2 Answers2

2

You can use an anonymous type, for instance:

var data = new { info1 = "info1Data", info2 = "info2Data", info3 = new { info3Data = new JArray() } };
var jsontext = JsonConvert.SerializeObject(data);
var message = new Message(Encoding.UTF8.GetBytes(jsontext));
await client.SendEventAsync(message);
Roman Kiss
  • 7,925
  • 1
  • 8
  • 21
  • Thank you a lot, i manage to get it to work with the format i had before. Thanks . My next concern will be how to insert data in the JArray, but as far as the question goes it is solved. Thanks. – Lopes May 14 '19 at 15:34
0

Try to escape the quotes by doubling them ("") in a raw string (@) as explained in the following post:

How to add double quotes to a string that is inside a variable?

For your example:

string format = @"{""info1"":""info1Data"",""info2"":""info2Data"",""info3"":""info3Data"":[]}}";
Arye
  • 381
  • 2
  • 7
  • First of all i would like to thank you for the fast response, however i'm still facing dificulties, and with the goal to clarify what exactly i'm doing i will post all the code regarding this issue bellow . `string format = @"{""info1"":""info1Data"",""info2"":""info2Data"",""info3"":""info3Data"":[]}}";` `var messageString1 = JsonConvert.SerializeObject(format);` `var message1 = new Message(Encoding.ASCII.GetBytes(messageString1));` `var json1 = JsonConvert.SerializeObject(format);` `client.SendEventAsync(message1);` – Lopes May 14 '19 at 14:01
  • and i'm still getting the following result in IoT Hub :{\"info1\":\"info1Data\",\"info2\":\"info2Data\",\"info3\":\"info3Data\":[]}} – Lopes May 14 '19 at 14:09
  • JsonConvert.SerializeObject accepts an object, you are passing a string object.. try to use a dynamic object: https://thewayofcode.wordpress.com/2012/09/18/c-dynamic-object-and-json-serialization-with-json-net/ – Arye May 14 '19 at 14:25
  • Something like: dynamic foo = new ExpandoObject(); foo.info1 = "info1Data"; foo.info2 = "info2Data"; ... string json = Newtonsoft.Json.JsonConvert.SerializeObject(foo) – Arye May 14 '19 at 14:31