多层嵌套Json,JArray的基本操作
分类:计算机编程

引用:

using Newtonsoft.Json.Linq;

Newtonsoft.Json.Net20.dll 下载请访问

1、JObject:基本的json对象

    /// <summary>
    /// Gets the j object.
    /// </summary>
    /// <returns></returns>
    public JObject GetJObject()
    {
        var obj = new JObject {{"Name", "Mark" } };
        return obj;
    }

图片 1

如何获取json里的某个属性(节点)值,对其删改,新增

在.net 2.0中提取这样的json

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;
    }

图片 2

//2.1 数组用JArray加载

{"name":"lily","age":23,"addr":{"city":guangzhou,"province":guangdong}}

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;
    }

图片 3

 

引用命名空间

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;
    }

图片 4

string jsonText = ``"[{'a':'aaa','b':'bbb','c':'ccc'},{'a':'aa','b':'bb,'c':'cc'}]"``;

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

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

 

可以把上面的JSON看成一个对象.你只要写对应的类即可

var mJObj = JArray.Parse(jsonText);

public class UserInfo

 

{

//需求,删除列表里的a节点的值为'aa'的项

public string name;

 

public int age;

IList<JToken> delList = ``new List<JToken>(); ``//存储需要删除的项

public address addr;

 

}

foreach (``var ss ``in mJObj )  ``//查找某个字段与值

public class address

{

{

if``(((JObject) ss)[``"a"``]==``'aa'``)

public string city;

 

public string province;
}

delList .add(ss);

然后在解析的地方这样写:

}

string jsonData="{"name":"lily","age":23,"addr":{"city":guangzhou,"province":guangdong}}";

 

UserInfo user=(UserInfo)JsonConvert.DeserializeObject(jsonData, typeof(UserInfo));

foreach (``var item ``in delList )  ``//移除mJObj  在delList 里的项

得到City的值只要:user.addr.City;

{

这样实现也行

 

JObject jsonObj = JObject.Parse(jsonData);

mJObj .remove(item);

string name=jsonObj ["name"].ToString();

}

string age=jsonObj ["age"].ToString();

//2.2 非数组用JObject加载 (这里主要以这个为例子)

string city=((JObject )jsonObj ["addr"])["city"].ToString();

 

string province=((JObject )jsonObj ["addr"])["province"].ToString();

string jsonText = ``"[{'a':'aaa','b':'bbb','c':'ccc'}]"``;

如 何这个json是动态的呢?譬如让你输入一个json,如{"name":"lily","age":23,"addr": {"city":guangzhou,"province":guangdong}}; 然后让你输入一个对象,如city,然后系统会输出guangzhou这个值,那这样的话,json就是动态生成的了,我想了解有没有读取这样的json 的方法。(注意,json是多级嵌套的。)

 

就用遍历

var mJObj = JObject.Parse(jsonText t);

public string GetJsonValue(JEnumerable<JToken> jToken,string key)
{
IEnumerator enumerator = jToken.GetEnumerator();
while (enumerator.MoveNext())
{
JToken jc = (JToken)enumerator.Current;

 

if (jc is JObject||((JProperty)jc).Value is JObject)
{
return GetJsonValue(jc.Children(), key);
}
else
{
if (((JProperty)jc).Name == key)
{

mJObj.Add() ``//新增,没试过

return ((JProperty)jc).Value.ToString();
}
}
}
return null;
}

 

在调用的时候:

var v1=mJObj[a].ToString()  ``//得到'aaa'的值

string jsonData = "{"name":"lily","age":23,"addr":{"city":"guangzhou","province":"guangdong"}}";
JObject jsonObj = JObject.Parse(jsonData);
Response.Write(GetJsonValue(jsonObj.Children(), "province"));

以上的例子可交互灵活使用

如果有多层嵌套的数组

 

string  jsonData = "{"addr":[{"city":"guangzhou","province":"guangdong"},{"city":"guiyang","province":"guizhou"}]}";
JObject  jsonObj = JObject.Parse(jsonData);
JArray  jar = JArray.Parse(jsonObj["addr"].ToString());
JObject  j = JObject.Parse(jar[0].ToString());
Response.Write(j["city"]);

注意事项,JArray 只能用来查找索引的项的对象,找到对象需要转换为 JObject,再查找对应的属性值

JSON转XML

 

string xmlstr=((XmlDocument)JsonConvert.DeserializeXmlNode(jsonData)).InnerXml.ToString();

其他写法补充

1、属性下嵌套json (非数组)遍历其包含的属性列表

var xx = ((mJObj["dim"])).Children().Values(); 

foreach (var item in xx)
{
var dimID = ((JObject) item)["id"];

}

转载:

本文由pc28.am发布于计算机编程,转载请注明出处:多层嵌套Json,JArray的基本操作

上一篇:国内值得关注的API集合,查询单词详细信息 下一篇:没有了
猜你喜欢
热门排行
精彩图文