-4

I have a situation where I received an input string with a random value contained there ("54403dd5-5f1d-4ba0-8477-9b16807ee285") basically that string is received from another source code but I just pasted there for reference, also notice that I split patterns in order to get a cleaner string output(this can be omitted). What I really need is how I can pick only that Id value up from there so I can process further. I also pasted the output generated with what I've done so far but not luck, If you have a better approach to get only this value without anything else I will appreciate.

String input = "\"{\"Protocol\":\"12345\",\"Version\":1,\"Timestamp\":\"2020-05-01T21:55:12.123456Z\",\"Assignment\":{\"Id\":\"54403dd5-5f1d-4ba0-8477-9b16807ee285\",\"Asset\":[]}}\"";
String pattern = @"\s-\s?[+*]?\s?-\s";
int found = 0;

String[] elements = System.Text.RegularExpressions.Regex.Split(input, pattern);
foreach (var element in elements)
    Console.WriteLine(element);

Console.WriteLine("\nWe want to retrieve only the Id string value. That is:");
foreach (string s in elements)
{
    found = s.IndexOf("Id");
    Console.WriteLine(s.Substring(found + 5));
}

Output:

"{"Protocol":"12345","Version":1,"Timestamp":"2020-05-01T21:55:12.123456Z","Assignment":{"Id":"54403dd5-5f1d-4ba0-8477-9b16807ee285","Asset":[]}}"

We want to retrieve only the Id string value. That is: 54403dd5-5f1d-4ba0-8477-9b16807ee285","Asset":[]}}"

Theodor Zoulias
  • 34,835
  • 7
  • 69
  • 104
Cesar
  • 49
  • 1
  • 3

1 Answers1

1

If you don't mind using the Newtonsoft.Json package, you could try this:

string input = "{\"Protocol\":\"12345\",\"Version\":1,\"Timestamp\":\"2020-05-01T21:55:12.123456Z\",\"Assignment\":{\"Id\":\"54403dd5-5f1d-4ba0-8477-9b16807ee285\",\"Asset\":[]}}";
var obj = JObject.Parse(input);
Guid id = obj.SelectToken("Assignment").SelectToken("Id").ToObject<Guid>();

Update

If you'd prefer to avoid the Newtonsoft package, you can do it this way using System.Text:

string input = "{\"Protocol\":\"12345\",\"Version\":1,\"Timestamp\":\"2020-05-01T21:55:12.123456Z\",\"Assignment\":{\"Id\":\"54403dd5-5f1d-4ba0-8477-9b16807ee285\",\"Asset\":[]}}";
using(var doc = JsonDocument.Parse(input))
{
    Guid id = doc.RootElement.GetProperty("Assignment").GetProperty("Id").GetGuid();
}
Connell.O'Donnell
  • 3,603
  • 11
  • 27
  • 61