0

I created an array and I want to send it to a C# application. I want to be able to use it as a C# string array so I can create a for loop where I can run some tasks.

Node.js (Express.js)

router.get('/arr', function(req,res,next) {
  var arr = ["orange", "plum", "strawberry", "lemon", "tangerine"];
  res.send(arr);
});

C# code.

public string Arr() {
  HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://10.0.2.2/arr");
  HttpWebResponse response = (HttpWebResponse)request.GetResponse();
  StreamReader stream = new StreamReader(response.GetResponseStream());
  string final_response = stream.ReadToEnd();
  stream.Dispose();
  return final_response;
 }

C# application's editor (This is an editor where I can do very limited stuff, so there's no way to import 3rd party packages but you can do basic stuff like http get/post, etc)

string Answer = Lib.Arr();

How can I create Answer as a string array? I tried creating Answer as string[] Answer but it says string can't get converted into string[], where am I wrong?

I'm new to C#.

salep
  • 1,332
  • 9
  • 44
  • 93
  • Your `final_response` is a string with the json, it isn't an array yet. Casting won't work. You actually need to parse it. If you had access to libraries, you could use Newtonsoft: http://www.newtonsoft.com/json . Depending on your editor, maybe you have access to [DataContractJsonSerializer](https://msdn.microsoft.com/en-us/library/bb908232.aspx). Here is an example how to use it:http://stackoverflow.com/questions/8204320/deserializing-a-simple-json-array-with-datacontractjsonserializer – vyrp Mar 25 '17 at 14:09

1 Answers1

1

If all you need to parse is an array of strings, then you can do something like this:

string trimmedAnswer = Lib.Arr().Trim(); // Remove whitespaces from the beginning and end
trimmedAnswer = trimmedAnswer.Substring(1, trimmedAnswer.Length - 1); // Remove [ and ] characters
string[] Answer = trimmedAnswer.Split(",").Select(s => s.Trim()).ToArray(); // Split every element by the commas, and remove any whitespaces 

But if you need to parse more complicated jsons, then you need something like this answer: https://stackoverflow.com/a/24891561/2420998

Community
  • 1
  • 1
vyrp
  • 890
  • 7
  • 15