我创建一个Web API。它的主要目的是向另一个服务器发出请求,并从该服务器获得响应。 我成功获得了特定服务器的响应。
我在下面得到响应(它的JSON格式)。
{
"id": "test@gmail.com",
"active": 1,
"is_logged": true,
"token": "hsja3t56yJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VybmFtZSI6InRlc3RAZHZlby5jb20iLCJwYXNzd29yZCI6InRlc3QyMDE4KyIsImV4cGlyZU9uIjoiMjAxOS0wNi0yMVQwNTozNzowOC4xODhaIn0.3wgGeL_HvcoEJJeEF7tj8jeXk2uIKpOoi9ewmK5yhteh",
"status": "OK",
"usertype": "TestUser",
"msg": "Login Successfull."
}
我尝试使用拆分功能进行分离
string[] sep = response.Split(',');
foreach (string any in sep)
Console.WriteLine(any);
//string[] colon = sep[0].Split(':');
string[][] colon = sep.Select(x => x.Split(':')).ToArray();
//int count = colon.Count();
for (int i = 0; i <= colon.Length; i++)
{
Console.WriteLine(colon[i][0]);
Console.WriteLine(colon[i][1]);
}
还有其他方法来分隔响应吗?我还将所有字段用于其他目的。
答案 0 :(得分:2)
根据您的响应属性创建一个类:
public class UserData
{
public string id { get; set; }
public int active { get; set; }
public bool is_logged { get; set; }
public string token { get; set; }
public string status { get; set; }
public string usertype { get; set; }
public string msg { get; set; }
}
在读取响应数据时,请使用JsonConvert.DeserializeObject
string response = "{\"id\":\"test @gmail.com\",\"active\":1,\"is_logged\":true,\"token\":\"hsja3t56yJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VybmFtZSI6InRlc3RAZHZlby5jb20iLCJwYXNzd29yZCI6InRlc3QyMDE4KyIsImV4cGlyZU9uIjoiMjAxOS0wNi0yMVQwNTozNzowOC4xODhaIn0.3wgGeL_HvcoEJJeEF7tj8jeXk2uIKpOoi9ewmK5yhteh\",\"status\":\"OK\",\"usertype\":\"TestUser\",\"msg\":\"Login Successfull.\"}";
var responseData = JsonConvert.DeserializeObject<UserData>(response);
//here the print in JSON Data
Console.WriteLine("id : " + responseData.id);
Console.WriteLine("active : " + responseData.active);
Console.WriteLine("is_logged : " + responseData.is_logged);
Console.WriteLine("token : " + responseData.token);
Console.WriteLine("status : " + responseData.status);
Console.WriteLine("usertype : " + responseData.usertype);
Console.WriteLine("msg : " + responseData.msg);
答案 1 :(得分:1)
这是我自己的示例,可以从JSON字符串获取属性,您可以使用它。
但是首先,您需要安装此软件包:-> Newtonsoft.Json.Linq以访问JObject
using System;
using Newtonsoft.Json.Linq;
public class Program
{
public static void Main()
{
string jsonString = "{\"firstname\":\"Alex Wu\",\"lastname\":\"type\"}";
JObject jObject = JObject.Parse(jsonString);
string firstname = (string)jObject.SelectToken("firstname");
string lastname = (string)
Console.WriteLine("{0}", firstname);
Console.ReadLine();
}
}
答案 2 :(得分:0)
通过添加NuGet包来使用Newtonsoft.json.dll, 然后将响应转换为json对象
JObject jo = JObject.Parse(searchCondition);
foreach (JToken child in jo.Children()) {
var prop = child as JProperty;
if (prop.Value != null && !string.IsNullOrEmpty(prop.Value.ToString())) {
string name=prop.Name;
string value = prop.Value;
//You can now do whatever with the values like put in a list of object
}
}