Home > Software engineering >  How to send a Json object to Arduino?
How to send a Json object to Arduino?

Time:06-14

I'm making a program in C# to send a JSON object to my arduino. I'm using a Newtonsoft Json library, I can only send it in string format... Is there another way to send the JSON object?

This way it gives an error because I'm not sending it in string format:

    public static void SendInfo(JObject data)
    {
        try
        {
            if (Port != null && Port.IsOpen)
            {
                Port.Write(data);

            }

        }
        catch (Exception e)
        {
            Console.WriteLine("Exception information: {0}", e);
        }

    }

This way it doesn't give an error because I'm converting the JSON object to a string:

        public static void SendInfo(JObject data)
    {
        try
        {
            if (Port != null && Port.IsOpen)
            {
                Port.Write(Convert.ToString(data));

            }

        }
        catch (Exception e)
        {
            Console.WriteLine("Exception information: {0}", e);
        }

    }

CodePudding user response:

JSON is a format that is based on human-readable text.

If the question is whether you can send JSON data as anything else than text, then the answer is: No. (Unless you encode or compress the JSON text, like for example using gzip compression).

If you don't want to send your data in the form of some text format, you cannot use JSON, because JSON is a text-based format. You would have to use some other (binary?) format other than Json that is not text-based.

CodePudding user response:

It is correct to convert to string. Arduino has libraries that allow you to reverse this process and thus you will get a similar object to JObject depending on which library you use. As a hint, I will add that before sending it is worth adding some start and end characters of the text being sent, for example: STX (0x02) and ETX (0x03). Thanks to this, on the Arduino side you will be sure that you are parsing the complete json string.

  • Related