[英]Simple way to extract specific data from string?
研究一种提取从计算机上下载的数据的方法
Webclient.Downloadstring();
为此,我将使用常规字符串作为示例。
通常,下载的字符串为:
var data = "{\"err\":[],\"msg\":[],\"state\":null," +
"rec\":{\"Vin\":\"1ABC2DEF3GH45678\"," +
"\"REG\":\"ST-ABC123\",\"int\":\"12345678\"," +
"\"Make\":\"GMC\",\"Model\":\"YUKON\"," +
"\"Type\":\"SUV\",\"Color\":\"black metallic\",";
我要获取的信息是Vin,注册,ID(int),品牌,型号,颜色等。
我一直遵循的方法如下。
public class Program
{
public static void Main(string[] args)
{
var data = "{\"err\":[],\"msg\":[],\"state\":null," +
"rec\":{\"Vin\":\"1ABC2DEF3GH45678\"," +
"\"REG\":\"ST-ABC123\",\"int\":\"12345678\"," +
"\"Make\":\"GMC\",\"Model\":\"YUKON\"," +
"\"Type\":\"SUV\",\"Color\":\"black metallic\",";
data = doc.Replace('{', ' ');
data = doc.Replace('"', ' ');
data = doc.Replace('}', ' ');
var sub = data.Split(':', ',');
for(int i = 0; i < sub.Length; i++)
{
sub[i] = sub[i].Trim();
/*Console.WriteLine("{0} : {1}", i, sub[i]);
Outputs :
0 : err
1 : []
2 : msg
3 : []
4 : state
5 : null
6 : rec
7 : Vin
8 : 1ABC2DEF3GH45678
9 : REG
10 : ST-ABC123
11 : int
12 : 12345678
13 : Make
14 : GMC
15 : Model
16 : YUKON
17 : Type
18 : SUV
19 : Color
20 : black metallic
21 :
*/
}
Vehicle vehicle = new Vehicle(sub[8], sub[10], sub[12], sub[14], sub[16], sub[18], sub[20]);
}
}
public class Vehicle
{
public string Vin { get; set; }
public string Registration { get; set; }
public string ID { get; set; }
public string Make { get; set; }
public string Model { get; set; }
public string VehicleType { get; set; }
public string Color { get; set; }
public string Nav { get; set; }
public string Transmission { get; set; }
public Vehicle(string _Vin, string _Reg, string _ID, string _Make, string _Model, string _Type, string _Color)
{
this.Vin = _Vin;
this.Registration = _Reg;
this.ID = _ID;
this.Make = _Make;
this.Model = _Model;
this.VehicleType = _Type;
this.Color = _Color;
}
}
我是否采用正确的方法? 有没有更简单的方法? 至于车辆等级,情况会很好吗?
它对我有用,只需要我的代码中的一些输入即可。
假设您只是在向我们显示的数据中缺少几个字符,那么将这个JSON解析为C#对象确实很容易。 例如,首先我们从一些类开始:
public class Data
{
public List<string> err { get; set; }
public List<string> msg { get; set; }
public string state { get; set; }
public Rec rec { get; set; }
}
public class Rec
{
public string Vin { get; set; }
public string REG { get; set; }
public string @int { get; set; }
public string Make { get; set; }
public string Model { get; set; }
public string Type { get; set; }
public string Color { get; set; }
}
现在使用Newtonsoft.JSON :
var result = JsonConvert.DeserializeObject<Data>(data);
注意:我假设err
和msg
作为string
数组, state
也是string
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.