如何在不使用Newtonsoft的情况下从复杂的json字符串获取令牌或元素

时间:2018-08-17 20:04:05

标签: c# json web-services plugins dynamics-365

好吧,我需要为Dynamics 365创建一个插件来从Web服务获取值,该插件会向我返回复杂的json数据。

我已经使用DataContractJsonSerializer及其ReadObject方法将json转换为c#对象。我的问题是我需要从json对象获取特定项。例如说名字,城市,国家。我想选择特定的标记,例如AddressInfo,City等。是否可以在不使用Newtonsoft.Json类的情况下使用它。我正在使用沙盒环境,所以我不想使用它。

"value": [
    {
"UserName": "russellwhyte",
        "FirstName": "Russell",
        "LastName": "Whyte",
        "Emails": [
            "Russell@example.com",
            "Russell@contoso.com"
        ],
        "AddressInfo": [
            {
                "Address": "187 Suffolk Ln.",
                "City": {
                    "CountryRegion": "United States",
                    "Name": "Boise",
                    "Region": "ID"
                }
            }
        ],
        "Gender": "Male",
        "Concurrency": 636701022117117603
    },
    {

        "UserName": "scottketchum",
        "FirstName": "Scott",
        "LastName": "Ketchum",
        "Emails": [
            "Scott@example.com"
        ],
        "AddressInfo": [
            {
                "Address": "2817 Milton Dr.",
                "City": {
                    "CountryRegion": "United States",
                    "Name": "Albuquerque",
                    "Region": "NM"
                }
            }
        ],
        "Gender": "Male",
        "Concurrency": 636701022117117603
}]

private void ConvertJsonToObject(ITracingService tracingService, object jsonData)
    {


        DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(List<PeopleInfo>));

        MemoryStream ms = new MemoryStream();

        StreamWriter writer = new StreamWriter(ms);

        writer.Write(jsonData);
        writer.Flush();

        ms.Position = 0;

        //tracingService.Trace("memory stream \n{0}", Encoding.UTF8.GetString(ms.ToArray(), 0, (int)ms.Length));
        //tracingService.Trace("Memory stream \n{0}", ser.ReadObject(ms));

        List<PeopleInfo> pi = (List<PeopleInfo>)ser.ReadObject(ms);

        foreach (PeopleInfo info in pi)
        {
            tracingService.Trace("Name: {0}", info.FirstName + " " + info.LastName);
        }
}

[DataContract]
public class PeopleInfo
{
    /*To ignore the value of this property just remove [DataMember]*/
    [DataMember]
    public string FirstName { get; set; }
    [DataMember]
    public string LastName { get; set; }
    [DataMember]
    public string Address { get; set; }

}

try
                {
                    WebClient client = new WebClient();
                    client.Headers[HttpRequestHeader.ContentType] = "application/json";

                    string serviceURL = "http://services.odata.org/V4/TripPinService/People";

                     object jsonData = client.UploadString(serviceURL,"");
                      ConvertJsonToObject(tracingService, jsonData);


                }

0 个答案:

没有答案