title: Returning Json of byte array in web api c#
body: <p>Hi I have developed a <code>Web API</code> in which I am taking some parameters in URL and then processing them. The protocol I am using is <code>Modbus</code>. It returns a byte array and in return, I want to get some specific string data from it. Below is my code</p>
  
  <pre><code>  public string GetData(int slaveId, int dataAddress, int registerCount)
      {
  
          //string hexValue = intValue.ToString("X");
          // Convert the hex string back to the number
          int slaveHex = int.Parse(slaveId.ToString("X"), System.Globalization.NumberStyles.HexNumber);
          int addressHex = int.Parse(dataAddress.ToString("X"), System.Globalization.NumberStyles.HexNumber);
          int countHex = int.Parse(registerCount.ToString("X"), System.Globalization.NumberStyles.HexNumber);
  
  
          //serial port settings and opening it
          var serialPort = new SerialPort("COM2", 9600, Parity.Even, 8, StopBits.One);
  
          serialPort.Open();
  
          var stream = new SerialStream(serialPort);
          stream.ReadTimeout = 200;
          // send request and waiting for response
          // the request needs: slaveId, dataAddress, registerCount            
          var responseBytes = stream.RequestFunc3(slaveHex, addressHex, countHex);
  
          // extract the content part (the most important in the response)
          var data = responseBytes.ToResponseFunc3().Data;         
  
          //Convert a byte array to string
          var stringFromByteArray = System.Text.Encoding.UTF8.GetString(data);
          serialPort.Close();
  
          return stringFromByteArray;
      }
  </code></pre>
  
  <p>The <code>data</code> contains an array of 14 bytes</p>
  
  <p><a href="https://i.stack.imgur.com/eYUi5.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/eYUi5.png" alt="enter image description here"></a></p>
  
  <p>The <code>stringFromByteArray</code> returns the following</p>
  
  <pre><code>"\0�\0�\0�\0\u0016\0\u0017\0\u0018\0\u001a"
  </code></pre>
  
  <p>As you can see in above the returned string is not as expected. I want exact values as in data byte array. </p>
  
  <p>The resulting output I want it to be in <code>Json response</code>. Like below </p>
  
  <pre><code>{
    [0] =&gt; "220",
    [1] =&gt; "230",
    [2] =&gt; "240", 
    [3] =&gt; "22",
    [4] =&gt; "23",
    [5] =&gt; "24",
    [6] =&gt; "26",
  } 
  </code></pre>
  
  <p>How can I do it? Any help would be highly appreciated.</p>