csharp JArray JObject JToken

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了csharp JArray JObject JToken相关的知识,希望对你有一定的参考价值。

public static JObject mergeJsonObjects(List<JObject> objects) {

    JObject json = new JObject();
    foreach(JObject JSONObject in objects) {
        foreach(var property in JSONObject) {
            string name = property.Key;
            JToken value = property.Value;

            json.Add(property.Key, property.Value);
        }
    }

    return json;
}
public void StronglyTypedSerializationTest()
{

    // Demonstrate deserialization from a raw string
    var album = new Album()
    {
        AlbumName = "Dirty Deeds Done Dirt Cheap",
        Artist = "AC/DC",
        Entered = DateTime.Now,
        YearReleased = 1976,
        Songs =  new List<Song>() 
        {
            new Song()
            {
                SongName = "Dirty Deeds Done Dirt Cheap",
                SongLength = "4:11"
            },
            new Song()
            {
                SongName = "Love at First Feel",
                SongLength = "3:10"
            }
        }
    };
            
    // serialize to string            
    string json2 = JsonConvert.SerializeObject(album,Formatting.Indented);

    Console.WriteLine(json2);

    // make sure we can serialize back
    var album2 = JsonConvert.DeserializeObject<Album>(json2);

    Assert.IsNotNull(album2);
    Assert.IsTrue(album2.AlbumName == "Dirty Deeds Done Dirt Cheap");
    Assert.IsTrue(album2.Songs.Count == 2);
}
public JObject PostAlbumJObject(JObject jAlbum)
{
    // dynamic input from inbound JSON
    dynamic album = jAlbum;

    // create a new JSON object to write out
    dynamic newAlbum = new JObject();

    // Create properties on the new instance
    // with values from the first
    newAlbum.AlbumName = album.AlbumName + " New";
    newAlbum.NewProperty = "something new";
    newAlbum.Songs = new JArray();
    
    foreach (dynamic song in album.Songs)
    {
        song.SongName = song.SongName + " New"; 
        newAlbum.Songs.Add(song);                
    }
            
    return newAlbum;
}
public void JsonArrayParsingTest()
{
    var jsonString = @"[
{
""Id"": ""b3ec4e5c"",
""AlbumName"": ""Dirty Deeds Done Dirt Cheap"",
""Artist"": ""AC/DC"",
""YearReleased"": 1976,
""Entered"": ""2012-03-16T00:13:12.2810521-10:00"",
""AlbumImageUrl"": ""http://ecx.images-amazon.com/images/I/61kTaH-uZBL._AA115_.jpg"",
""AmazonUrl"": ""http://www.amazon.com/gp/product/…ASIN=B00008BXJ4"",
""Songs"": [
    {
    ""AlbumId"": ""b3ec4e5c"",
    ""SongName"": ""Dirty Deeds Done Dirt Cheap"",
    ""SongLength"": ""4:11""
    },
    {
    ""AlbumId"": ""b3ec4e5c"",
    ""SongName"": ""Love at First Feel"",
    ""SongLength"": ""3:10""
    },
    {
    ""AlbumId"": ""b3ec4e5c"",
    ""SongName"": ""Big Balls"",
    ""SongLength"": ""2:38""
    }
]
},
{
""Id"": ""7b919432"",
""AlbumName"": ""End of the Silence"",
""Artist"": ""Henry Rollins Band"",
""YearReleased"": 1992,
""Entered"": ""2012-03-16T00:13:12.2800521-10:00"",
""AlbumImageUrl"": ""http://ecx.images-amazon.com/images/I/51FO3rb1tuL._SL160_AA160_.jpg"",
""AmazonUrl"": ""http://www.amazon.com/End-Silence-Rollins-Band/dp/B0000040OX/ref=sr_1_5?ie=UTF8&qid=1302232195&sr=8-5"",
""Songs"": [
    {
    ""AlbumId"": ""7b919432"",
    ""SongName"": ""Low Self Opinion"",
    ""SongLength"": ""5:24""
    },
    {
    ""AlbumId"": ""7b919432"",
    ""SongName"": ""Grip"",
    ""SongLength"": ""4:51""
    }
]
}
]";

    JArray jsonVal = JArray.Parse(jsonString) as JArray;
    dynamic albums = jsonVal;

    foreach (dynamic album in albums)
    {
        Console.WriteLine(album.AlbumName + " (" + album.YearReleased.ToString() + ")");
        foreach (dynamic song in album.Songs)
        {
            Console.WriteLine("\t" + song.SongName);
        }
    }

    Console.WriteLine(albums[0].AlbumName);
    Console.WriteLine(albums[0].Songs[1].SongName);
}
public void JObjectOutputTest()
{
    // strong typed instance 
    var jsonObject = new JObject();
                        
    // you can explicitly add values here using class interface
    jsonObject.Add("Entered", DateTime.Now);

    // or cast to dynamic to dynamically add/read properties    dynamic album = jsonObject;

    album.AlbumName = "Dirty Deeds Done Dirt Cheap";
    album.Artist = "AC/DC";
    album.YearReleased = 1976;

    album.Songs = new JArray() as dynamic;
            
    dynamic song = new JObject();
    song.SongName = "Dirty Deeds Done Dirt Cheap";
    song.SongLength = "4:11";
    album.Songs.Add(song);

    song = new JObject();
    song.SongName = "Love at First Feel";
    song.SongLength = "3:10";
    album.Songs.Add(song);

    Console.WriteLine(album.ToString());
}
    JArray albums = JArray.Parse(jsonString) as JArray;

    // pick out one album
    JObject jalbum = albums[0] as JObject;

    // Copy to a static Album instance
    Album album = jalbum.ToObject<Album>();
            //将json转换为JObject
            JObject jObj = JObject.Parse(json);
            JToken colleagues = jObj["Colleagues"];
            colleagues[0]["Age"] = 45;
            jObj["Colleagues"] = colleagues;//修改后,再赋给对象
            Console.WriteLine(jObj.ToString());
            
            
            JObject jObj = JObject.Parse(json);
            jObj.Remove("Colleagues");//跟的是属性名称
            Console.WriteLine(jObj.ToString());
            
            
            JObject jObj = JObject.Parse(json);
            jObj["Colleagues"][1].Remove();
            Console.WriteLine(jObj.ToString());
            
            JObject jObj = JObject.Parse(json);
            JToken name = jObj.SelectToken("Name");
            Console.WriteLine(name.ToString());
            
            JObject jObj = JObject.Parse(json);
            var names = jObj.SelectToken("Colleagues").Select(p => p["Name"]).ToList();
            foreach (var name in names)
            Console.WriteLine(name.ToString());
            
            
我们发现Jack的信息中少了部门信息,要求我们必须添加在Age的后面
//将json转换为JObject
JObject jObj = JObject.Parse(json);
jObj["Age"].Parent.AddAfterSelf(new JProperty("Department", "Personnel Department"));
Console.WriteLine(jObj.ToString());

现在我们又发现,Jack公司来了一个新同事Linda
//将json转换为JObject
JObject jObj = JObject.Parse(json);
JObject linda = new JObject(new JProperty("Name", "Linda"), new JProperty("Age", "23"));
jObj["Colleagues"].Last.AddAfterSelf(linda);
Console.WriteLine(jObj.ToString());     
            
foreach (JObject items in _JArray)  
{  
    foreach (var item in items)  
    {  
        str.Append(item.Key + ":" + item.Value + ",");  
    }  
}  

以上是关于csharp JArray JObject JToken的主要内容,如果未能解决你的问题,请参考以下文章

如何在不添加新 JObject 键/名称的情况下将 JArray 添加到 JObject 中?

JObject 用法 JProperty 用法JArray 用法 Linq 转 Json

如何将 JArray 的所有元素添加到 C# 中的 JObject?

JObject& JArray操作

C# JArray与JObject 的使用

JArray数组每个JObject对象添加一个键值对