0

I'm trying to get some part of string by substring and this is my string :{"samanState":"OK","samanResNum":"97d590e2-9ce3-49f9-85cf-2228b33cad57","samanTraceNo":"479936"} I can't do something like this : substring(8,16) because this string is change every time. I want to get 479936 from that. I'm sure TraceNo":" is static and never change so I did this :

<td>@(bankDepositHistoryItem.AdditionalData.Substring
                                            (bankDepositHistoryItem.AdditionalData.IndexOf("TraceNo\":\""),
                                            bankDepositHistoryItem.AdditionalData.Length- bankDepositHistoryItem.AdditionalData.IndexOf("TraceNo\":\"")-2)) </td>

but the out put is : TraceNo":"479936 How should I get this : 479936 I have to say that I Know this is possible with serialize and deserialize but I want to know if this is possible with substring or split or methods like these. Many thanks

Ali Eshghi
  • 1,131
  • 1
  • 13
  • 30

2 Answers2

0

That is a JSON string, so I would first convert the string to a .NET object using the popular Json.NET framework library.

After adding the Newtonsoft.Json NuGet package to your project, your code would look something like this:

@using Newtonsoft.Json.Linq //add this to your Razor page or to _ViewImports.cshtml

<td>@(JObject.Parse(bankDepositHistoryItem)["samanTraceNo"])</td>
Versailles
  • 441
  • 2
  • 6
0

If you still want to parse the string, you can use a couple of handy string extension methods (I have variations for integers and Regex as well):

public static string Past(this string s, string starter) {
    var starterPos = s.IndexOf(starter);
    return starterPos == -1 ? String.Empty : s.Substring(starterPos + starter.Length);
}
public static string UpTo(this string s, string stopper) {
    var stopPos = s.IndexOf(stopper);
    return (stopPos >= 0) ? s.Substring(0, stopPos) : s;
}

Then extract with:

var ans = bankDepositHistoryItem.Past("\"samanTraceNo\":\"").UpTo("\"");
NetMage
  • 26,163
  • 3
  • 34
  • 55