Csharp/C#教程:如何解析C#中的示例字符串分享


如何解析C#中的示例字符串

我有这个字符串

[ { "url_short":"https://sample.com/8jyKHv", "url_long":"https://www.sample.com/", "type":0 } ] 

我想要的是获取https://sample.com/8jyKHv并将其翻译为

 https://sample.com/8jyKHv 

可能吗?

JSON方式肯定是推荐的,但不能说明它。 以下是正则表达式的替代方法:

 Regex rgxUrl = new Regex(""url_short":"(.*?)",""); Match mUrl = rgxUrl.Match(yourString); string url = Regex.Replace(mUrl.Groups[1].Value, @"", ""); 

这个字符串是JSON。

您可以使用JSON.NET解析它。

例:

 using System; using System.Collections.Generic; using Newtonsoft.Json; public class RootObject { public string url_short { get; set; } public string url_long { get; set; } public int type { get; set; } } public class Program { static public void Main() { string j = "[{"url_short":"http:\/\/sample.com\/8jyKHv","url_long":"http:\/\/www.sample.com\/","type":0}]"; List ro = JsonConvert.DeserializeObject>(j); Console.WriteLine(ro[0].url_short); } } 

响应:

https://sample.com/8jyKHv

试试这个

创建一个如下所示的类

注意:您可以使用visual studio中的“选择性粘贴”选项来生成与JSON相关的所有类

编辑 – >选择性粘贴 – >将Json粘贴为类

它将创建与JSON相关的所有类

  public class url_details { public string url_short { get; set; } public string url_long { get; set; } public int type { get; set; } } public List json_deserialized() { string json = "[{"url_short":"http:\/\/sample.com\/8jyKHv","url_long":"http:\/\/www.sample.com\/","type":0}]"; List items = new List(); items = JsonConvert.DeserializeObject>(json); return items; } 

您可以访问下面的元素

  List obj = json_deserialized(); string url_short = obj[0].url_short; 

该字符串是一个JSON字符串,因此您可以创建一个类来获取这样的值

 public class Rootobject { public Class1[] Property1 { get; set; } } public class Class1 { public string url_short { get; set; } public string url_long { get; set; } public int type { get; set; } } 

在这堂课之后你可以得到这样的数据

上述就是C#学习教程:如何解析C#中的示例字符串分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!

 string json = "[{"url_short":"https://sample.com/8jyKHv","url_long":"https://www.sample.com/","type":0}]"; List ro = JsonConvert.DeserializeObject>(json); string ururl = ro[0].Propert1[0].url_short; 

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/943147.html

(0)
上一篇 2021年11月14日
下一篇 2021年11月14日

精彩推荐