这篇文章介绍了C#使用JArray和JObject封装JSON对象的方法,文中通过示例代码介绍的非常详细。对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
1、JObject:基本的json对象
/// <summary>
/// Gets the j object.
/// </summary>
/// <returns></returns>
public JObject GetJObject()
{
var obj = new JObject {{"Name", "Mark" } };
return obj;
}
2、JObject:嵌套子对象(JObject嵌JObject)
/// <summary>
/// Gets the j object.
/// </summary>
/// <returns></returns>
public JObject GetJObject()
{
var obj = new JObject {{"Name", "Mark"}, {"Age", 8 }};
var info = new JObject {{"Phone", "132****7777"}, {"Gender", "男"}};
obj.Add("Info", info);
return obj;
}
3、JArray:基本json对象中的数组
/// <summary>
/// Gets the j array.
/// </summary>
/// <returns></returns>
public JArray GetJArray()
{
var jarray = new JArray();
var mark = new JObject { { "Name", "Mark" }, { "Age", 8 } };
var jack = new JObject { { "Name", "Jack" }, { "Age", 9 } };
jarray.Add(mark);
jarray.Add(jack);
return jarray;
}
4、JArray:多个json对象数组
/// <summary>
/// Gets the j array.
/// </summary>
/// <returns></returns>
public JObject GetJArray()
{
var obj = new JObject();
var student = new JArray
{
new JObject {{ "Name", "Mark" }, { "Age", 8 } },
new JObject {{ "Name", "Jack" }, { "Age", 9 } }
};
var results = new JArray
{
new JObject {{ "Subject", "语文"}, { "Score", 100}},
new JObject {{ "Subject", "数学" }, { "Score", 88}}
};
obj.Add("Student", student);
obj.Add("Results", results);
return obj;
}
5、JArray:json数组嵌套数组(一个学生对应多个课程分数)
/// <summary>
/// Gets the results.
/// </summary>
/// <returns></returns>
public JObject GetResults()
{
var mark = new JObject { { "Name", "Mark" }, { "Age", "8" } };
var results = new JArray
{
new JObject {{ "Subject", "语文"}, { "Score", 100}},
new JObject {{ "Subject", "数学" }, { "Score", 88}}
};
mark.Add("Results", results);
return mark;
}
总结:写接口的时候,类似上面的5种情况经常会遇到,有时候会弄糊涂,算一次简单的复习吧。
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对得得之家的支持。如果你想了解更多相关内容请查看下面相关链接
沃梦达教程
本文标题为:C#使用JArray和JObject封装JSON对象
基础教程推荐
猜你喜欢
- 一个读写csv文件的C#类 2022-11-06
- C# windows语音识别与朗读实例 2023-04-27
- C# List实现行转列的通用方案 2022-11-02
- linux – 如何在Debian Jessie中安装dotnet core sdk 2023-09-26
- C# 调用WebService的方法 2023-03-09
- C#控制台实现飞行棋小游戏 2023-04-22
- C#类和结构详解 2023-05-30
- ZooKeeper的安装及部署教程 2023-01-22
- unity实现动态排行榜 2023-04-27
- winform把Office转成PDF文件 2023-06-14