如何在C#中从JSON字符串中获取一些值?

mpgws1up  于 2023-04-08  发布在  C#
关注(0)|答案(6)|浏览(232)

我有一个字符串,我想从它得到一些值。
我的字符串看起来像:
字符串1:

"{\r\n   \"id\": \"100000280905615\",
 \r\n \"name\": \"Jerard Jones\",
 \r\n   \"first_name\": \"Jerard\",
 \r\n   \"last_name\": \"Jones\",
 \r\n   \"link\": \"https://www.facebook.com/Jerard.Jones\",
 \r\n   \"username\": \"Jerard.Jones\",
 \r\n   \"gender\": \"female\",
 \r\n   \"locale\": \"en_US\"\r\n}"

字符串2:

"{\r\n   \"id\": \"100000390001929\",
  \r\n   \"name\": \"\\u05d1\\u05d2\\u05e8\\u15dc\\u25d9 \\u05d1\\u05e8\\u05d5\\u05e9\",
  \r\n   \"first_name\": \"\\u05d4\\u05d2\\u05e7\\u02dc\\u05d9\",
  \r\n   \"last_name\": \"\\u05d1\\u05e8\\u05d5\\u05e9\",
  \r\n   \"link\": "https://www.facebook.com/people/\\u05d2\\u05d1\\u05e@\\u05dc\\u05d9-\\u05d1\\u05e8\\u05d4\\u05e9/100000390001929\",
  \r\n   \"gender\": \"female\",
  \r\n   \"locale\": \"he_IL\"\r\n}"

不幸的是,有一种情况,字符串将由相同的概念,但没有一些参数:
字符串3:

"{\r\n   \"id\": \"100000390001929\",
  \r\n   \"last_name\": \"\\u05d1\\u05e8\\u05d5\\u05e9\",
  \r\n   \"gender\": \"female\",
  \r\n   \"locale\": \"he_IL\"\r\n}"

如何获取以下值:idfirst_namelast_namegenderlocale
任何帮助赞赏!

rnmwe5a2

rnmwe5a21#

你的字符串是JSON格式的,所以你需要将它 * 解析 * 成一个对象,你可以使用JSON.NET
下面是一个如何将JSON字符串解析为动态对象的示例:

string source = "{\r\n   \"id\": \"100000280905615\", \r\n \"name\": \"Jerard Jones\",  \r\n   \"first_name\": \"Jerard\", \r\n   \"last_name\": \"Jones\", \r\n   \"link\": \"https://www.facebook.com/Jerard.Jones\", \r\n   \"username\": \"Jerard.Jones\", \r\n   \"gender\": \"female\", \r\n   \"locale\": \"en_US\"\r\n}";
dynamic data = JObject.Parse(source);
Console.WriteLine(data.id);
Console.WriteLine(data.first_name);
Console.WriteLine(data.last_name);
Console.WriteLine(data.gender);
Console.WriteLine(data.locale);

编码快乐!

pw9qyyiw

pw9qyyiw2#

下面的代码为我工作。
用途:

using System.IO;
using System.Net;
using Newtonsoft.Json.Linq;

验证码:

using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                {
                    using (Stream responseStream = response.GetResponseStream())
                    {
                        using (StreamReader responseReader = new StreamReader(responseStream))
                        {
                            string json = responseReader.ReadToEnd();
                            string data = JObject.Parse(json)["id"].ToString();
                        }
                    }
                }

//json = {"kind": "ALL", "id": "1221455", "longUrl": "NewURL"}
kyks70gy

kyks70gy3#

我的弦

var obj = {"Status":0,"Data":{"guid":"","invitationGuid":"","entityGuid":"387E22AD69-4910-430C-AC16-8044EE4A6B24443545DD"},"Extension":null}

以下代码用于获取guid:

var userObj = JObject.Parse(obj);
var userGuid = Convert.ToString(userObj["Data"]["guid"]);
zf9nrax1

zf9nrax14#

使用System.Text.Json的.NET 6版本

using System;
                    
public class Program
{
    public static void Main()
    {
        var jsonString = @"{ ""id"" : 123 }";
        
        //parse it
        var yourObject = System.Text.Json.JsonDocument.Parse(jsonString);
        //retrieve the value
        var id= yourObject.RootElement
                          .GetProperty("id");
        
        Console.WriteLine(id);
    }
}

要检索嵌套的属性,您可以链接GetProperty调用。作为一个更高级的示例:

//access first element of array "persons" get nested property "age" 
var age = yourObject.rootElement.GetProperty("persons")[0]
                                .GetProperty("age");
cnwbcb6i

cnwbcb6i5#

创建一个类,如下所示:

public class Data
{
    public string Id {get; set;}
    public string Name {get; set;}
    public string First_Name {get; set;}
    public string Last_Name {get; set;}
    public string Username {get; set;}
    public string Gender {get; set;}
    public string Locale {get; set;}
}

(我不是100%确定,但如果这不起作用,你需要使用[DataContract][DataMember]来代替DataContractJsonSerializer
然后创建JSonSerializer

private static readonly XmlObjectSerializer Serializer = new DataContractJsonSerializer(typeof(Data));

并反序列化对象:

// convert string to stream
byte[] byteArray = Encoding.UTF8.GetBytes(contents);
using(var stream = new MemoryStream(byteArray))
{
    (Data)Serializer.ReadObject(stream);
}
f1tvaqid

f1tvaqid6#

您也可以使用此替代方法指定预期的类型:

using Newtonsoft.Json;

class Person {
    public string Name { get; set; }
    public int Age { get; set; }
}

string jsonString = "{\"name\": \"John\", \"age\": 30}";

Person person = JsonConvert.DeserializeObject<Person>(jsonString);

相关问题