如何从源中获取特定字符串?

时间:2016-01-24 11:16:53

标签: c# json

我想创建一个显示当前信息的应用程序,我可以使用简单的(至少看起来很简单)API来获取信息。

现在,您可以通过访问网站来使用API​​,然后输入用户名。该网址会产生类似site.web/api/public/user?name=Usename的内容。 在该页面上是我需要的所有信息,以一行'代码'的形式。

{"uniqueId":"hhus-7723dec98ecb9bc6643f10588e0bb3f4","name":"Username","figureString":"hr-125-40.hd-209-1369.ch-210-64.lg-270-1408.he-3329-1408-1408","selectedBadges":[],"motto":"sample txt","memberSince":"2012-08-25T14:01:04.000+0000","profileVisible":true,"lastWebAccess":null}

我想提取这些信息并将其显示在我的程序中,例如:

{"uniqueId":"this is an ID"}

我只想要显示实际ID:这是一个ID。

感谢您的帮助!

4 个答案:

答案 0 :(得分:2)

您收到的格式称为JSON。有很多库可以轻松阅读,C#中使用最广泛的是JSON.NET

如果您只需要提取一个属性,则可以执行以下操作:

string json = ...
var obj = JObject.Parse(json);
string uniqueId = obj["uniqueId"].Value<string>();

如果您还需要其他属性,则可能更容易使用反序列化:创建一个与JSON对象具有相同属性的类,并使用JsonConvert.DeserializeObject将JSON读入该类的实例。

答案 1 :(得分:1)

您引用的一行代码是JSON数据。它以&#34; key&#34;:&#34; value&#34;,&#34; key:value&#34;,&#34; key:value&#34;的格式存储等等。

你应该看看Newtonsoft.Json,它可以帮你完成这个:解析JSON数据:)

https://www.nuget.org/packages/Newtonsoft.Json/

答案 2 :(得分:1)

为你们所有人......

using System.IO;
using System.Net;
using Newtonsoft.Json.Linq;
...
WebClient client = new WebClient();
Stream stream = client.OpenRead("http://site.web/api/public/user?name=Usename");
StreamReader reader = new StreamReader(stream);
string userJson = reader.ReadLine();
reader.Close();

JObject jObject = JObject.Parse(userJson);
string uniqueId = (string)jObject["uniqueId"];

答案 3 :(得分:1)

这是Json的一个例子。如果要将数据反序列化为您定义的类,则最安全的方式。

这样的课程看起来像这样:

public class MyClass
{
    public string uniqueId { get; set; }
}

如果你有一个字符串中的数据,你可以使用Newtonsoft.Json nuget包反序列化它。

MyClass obj = JsonConvert.Deserialize<MyClass>(myJsonString);

如果从http获取数据,则更容易使用可以为您执行反序列化的客户端。这样的客户端可以在nuget包Microsoft.AspNet.WebApi.Client

中找到
using(var client = new HttpClient())
{
    var response = await client.GetAsync(myUrl);
    response.EnsureSuccessStatusCode();
    MyClass obj = await response.Content.ReadAsAsync<MyClass>();
}

当然,这假定服务器符合标准,并将其内容类型指定为application / json

奖励:您反序列化的课程可以通过网站上的示例自动生成:http://json2csharp.com/