简体   繁体   English

UWP使用JSON数据创建列表

[英]UWP create list using JSON data

OK. 好。 I have sent a GET request to SharePoint and received a string back: 我已向SharePoint发送了一个GET请求并收到了一个字符串:

"{\"@odata.context\":\"https://graph.microsoft.com/v1.0/$metadata#sites('XXXXX.sharepoint.com%2C495435b4-60c3-49b7-8f6e-1d262a120ae5%2C0fad9f67-35a8-4c0b-892e-113084058c0a')/lists('18a725ac-83ef-48fb-a5cb-950ca2378fd0')/items\",\"value\":[{\"@odata.etag\":\"\\\"a69b1840-239d-42ed-9b20-8789761fb06a,3\\\"\",\"createdDateTime\":\"2018-08-25T22:44:16Z\",\"eTag\":\"\\\"a69b1840-239d-42ed-9b20-8789761fb06a,3\\\"\",\"id\":\"9\",\"lastModifiedDateTime\":\"2018-08-25T22:44:16Z\",\"webUrl\":\"https://XXXXX.sharepoint.com/sites/GeneratorApp/Lists/GenApp/9_.000\",\"createdBy\":{\"user\":{\"email\":\"XXXXX@XXXXX.com\",\"id\":\"b0465821-e891-4f44-9e18-27e875f1b75d\",\"displayName\":\"XXXXX\"}},\"lastModifiedBy\":{\"user\":{\"email\":\"XXXXX@XXXXX.com\",\"id\":\"b0465821-e891-4f44-9e18-27e875f1b75d\",\"displayName\":\"XXXXX\"}},\"parentReference\":{},\"contentType\":{\"id\":\"0x0100E19591A4ECA81542AEA41A6AAFED6781\"},\"fields@odata.context\":\"https://graph.microsoft.com/v1.0/$metadata#sites('XXXXX.sharepoint.com%2C495435b4-60c3-49b7-8f6e-1d262a120ae5%2C0fad9f67-35a8-4c0b-892e-113084058c0a')/lists('18a725ac-83ef-48fb-a5cb-950ca2378fd0')/items('9')/fields/$entity\",\"fields\":{\"@odata.etag\":\"\\\"a69b1840-239d-42ed-9b20-8789761fb06a,3\\\"\",\"SerialNumber\":\"20180824-1353-DC6-Generator-A\",\"id\":\"9\"}},{\"@odata.etag\":\"\\\"13f60f9e-1bf2-4803-93b9-c45234963d47,3\\\"\",\"createdDateTime\":\"2018-08-25T22:45:55Z\",\"eTag\":\"\\\"13f60f9e-1bf2-4803-93b9-c45234963d47,3\\\"\",\"id\":\"10\",\"lastModifiedDateTime\":\"2018-08-25T22:45:55Z\",\"webUrl\":\"https://XXXXX.sharepoint.com/sites/GeneratorApp/Lists/GenApp/10_.000\",\"createdBy\":{\"user\":{\"email\":\"XXXXX@XXXXX.com\",\"id\":\"b0465821-e891-4f44-9e18-27e875f1b75d\",\"displayName\":\"XXXXX\"}},\"lastModifiedBy\":{\"user\":{\"email\":\"XXXXX@XXXXX.com\",\"id\":\"b0465821-e891-4f44-9e18-27e875f1b75d\",\"displayName\":\"XXXXX\"}},\"parentReference\":{},\"contentType\":{\"id\":\"0x0100E19591A4ECA81542AEA41A6AAFED6781\"},\"fields@odata.context\":\"https://graph.microsoft.com/v1.0/$metadata#sites('XXXXX.sharepoint.com%2C495435b4-60c3-49b7-8f6e-1d262a120ae5%2C0fad9f67-35a8-4c0b-892e-113084058c0a')/lists('18a725ac-83ef-48fb-a5cb-950ca2378fd0')/items('10')/fields/$entity\",\"fields\":{\"@odata.etag\":\"\\\"13f60f9e-1bf2-4803-93b9-c45234963d47,3\\\"\",\"SerialNumber\":\"20180824-1416-DC6-Generator-B\",\"id\":\"10\"}},{\"@odata.etag\":\"\\\"00024848-0d4e-4ee8-b018-f1653af2a577,3\\\"\",\"createdDateTime\":\"2018-08-25T22:47:30Z\",\"eTag\":\"\\\"00024848-0d4e-4ee8-b018-f1653af2a577,3\\\"\",\"id\":\"11\",\"lastModifiedDateTime\":\"2018-08-25T22:47:30Z\",\"webUrl\":\"https://XXXXX.sharepoint.com/sites/GeneratorApp/Lists/GenApp/11_.000\",\"createdBy\":{\"user\":{\"email\":\"XXXXX@XXXXX.com\",\"id\":\"b0465821-e891-4f44-9e18-27e875f1b75d\",\"displayName\":\"XXXXX\"}},\"lastModifiedBy\":{\"user\":{\"email\":\"XXXXX@XXXXX.com\",\"id\":\"b0465821-e891-4f44-9e18-27e875f1b75d\",\"displayName\":\"XXXXX\"}},\"parentReference\":{},\"contentType\":{\"id\":\"0x0100E19591A4ECA81542AEA41A6AAFED6781\"},\"fields@odata.context\":\"https://graph.microsoft.com/v1.0/$metadata#sites('XXXXX.sharepoint.com%2C495435b4-60c3-49b7-8f6e-1d262a120ae5%2C0fad9f67-35a8-4c0b-892e-113084058c0a')/lists('18a725ac-83ef-48fb-a5cb-950ca2378fd0')/items('11')/fields/$entity\",\"fields\":{\"@odata.etag\":\"\\\"00024848-0d4e-4ee8-b018-f1653af2a577,3\\\"\",\"SerialNumber\":\"20180824-1438-DC6-Generator-R\",\"id\":\"11\"}},{\"@odata.etag\":\"\\\"7c8e80ed-6fea-408a-9594-2b7b13e3691b,3\\\"\",\"createdDateTime\":\"2018-08-25T23:02:43Z\",\"eTag\":\"\\\"7c8e80ed-6fea-408a-9594-2b7b13e3691b,3\\\"\",\"id\":\"12\",\"lastModifiedDateTime\":\"2018-08-25T23:02:43Z\",\"webUrl\":\"https://XXXXX.sharepoint.com/sites/GeneratorApp/Lists/GenApp/12_.000\",\"createdBy\":{\"user\":{\"email\":\"XXXXX@XXXXX.com\",\"id\":\"b0465821-e891-4f44-9e18-27e875f1b75d\",\"displayName\":\"XXXXX\"}},\"lastModifiedBy\":{\"user\":{\"email\":\"XXXXX@XXXXX.com\",\"id\":\"b0465821-e891-4f44-9e18-27e875f1b75d\",\"displayName\":\"XXXXX\"}},\"parentReference\":{},\"contentType\":{\"id\":\"0x0100E19591A4ECA81542AEA41A6AAFED6781\"},\"fields@odata.context\":\"https://graph.microsoft.com/v1.0/$metadata#sites('XXXXX.sharepoint.com%2C495435b4-60c3-49b7-8f6e-1d262a120ae5%2C0fad9f67-35a8-4c0b-892e-113084058c0a')/lists('18a725ac-83ef-48fb-a5cb-950ca2378fd0')/items('12')/fields/$entity\",\"fields\":{\"@odata.etag\":\"\\\"7c8e80ed-6fea-408a-9594-2b7b13e3691b,3\\\"\",\"SerialNumber\":\"20180824-1456-DC6-Generator-C\",\"id\":\"12\"}}]}"

Which will JObject.Parse to this: 哪个JObject.Parse会这样:

{{
  "@odata.context": "https://graph.microsoft.com/v1.0/$metadata#sites('XXXXX.sharepoint.com%2C495435b4-60c3-49b7-8f6e-1d262a120ae5%2C0fad9f67-35a8-4c0b-892e-113084058c0a')/lists('18a725ac-83ef-48fb-a5cb-950ca2378fd0')/items",
  "value": [
    {
      "@odata.etag": "\"a69b1840-239d-42ed-9b20-8789761fb06a,3\"",
      "createdDateTime": "2018-08-25T22:44:16Z",
      "eTag": "\"a69b1840-239d-42ed-9b20-8789761fb06a,3\"",
      "id": "9",
      "lastModifiedDateTime": "2018-08-25T22:44:16Z",
      "webUrl": "https://XXXXX.sharepoint.com/sites/GeneratorApp/Lists/GenApp/9_.000",
      "createdBy": {
        "user": {
          "email": "XXXXX@XXXXX.com",
          "id": "b0465821-e891-4f44-9e18-27e875f1b75d",
          "displayName": "XXXXX"
        }
      },
      "lastModifiedBy": {
        "user": {
          "email": "XXXXX@XXXXX.com",
          "id": "b0465821-e891-4f44-9e18-27e875f1b75d",
          "displayName": "XXXXX"
        }
      },
      "parentReference": {},
      "contentType": {
        "id": "0x0100E19591A4ECA81542AEA41A6AAFED6781"
      },
      "fields@odata.context": "https://graph.microsoft.com/v1.0/$metadata#sites('XXXXX.sharepoint.com%2C495435b4-60c3-49b7-8f6e-1d262a120ae5%2C0fad9f67-35a8-4c0b-892e-113084058c0a')/lists('18a725ac-83ef-48fb-a5cb-950ca2378fd0')/items('9')/fields/$entity",
      "fields": {
        "@odata.etag": "\"a69b1840-239d-42ed-9b20-8789761fb06a,3\"",
        "SerialNumber": "20180824-1353-DC6-Generator-A",
        "id": "9"
      }
    },
    {
      "@odata.etag": "\"13f60f9e-1bf2-4803-93b9-c45234963d47,3\"",
      "createdDateTime": "2018-08-25T22:45:55Z",
      "eTag": "\"13f60f9e-1bf2-4803-93b9-c45234963d47,3\"",
      "id": "10",
      "lastModifiedDateTime": "2018-08-25T22:45:55Z",
      "webUrl": "https://XXXXX.sharepoint.com/sites/GeneratorApp/Lists/GenApp/10_.000",
      "createdBy": {
        "user": {
          "email": "XXXXX@XXXXX.com",
          "id": "b0465821-e891-4f44-9e18-27e875f1b75d",
          "displayName": "XXXXX"
        }
      },
      "lastModifiedBy": {
        "user": {
          "email": "XXXXX@XXXXX.com",
          "id": "b0465821-e891-4f44-9e18-27e875f1b75d",
          "displayName": "XXXXX"
        }
      },
      "parentReference": {},
      "contentType": {
        "id": "0x0100E19591A4ECA81542AEA41A6AAFED6781"
      },
      "fields@odata.context": "https://graph.microsoft.com/v1.0/$metadata#sites('XXXXX.sharepoint.com%2C495435b4-60c3-49b7-8f6e-1d262a120ae5%2C0fad9f67-35a8-4c0b-892e-113084058c0a')/lists('18a725ac-83ef-48fb-a5cb-950ca2378fd0')/items('10')/fields/$entity",
      "fields": {
        "@odata.etag": "\"13f60f9e-1bf2-4803-93b9-c45234963d47,3\"",
        "SerialNumber": "20180824-1416-DC6-Generator-B",
        "id": "10"
      }
    },
    {
      "@odata.etag": "\"00024848-0d4e-4ee8-b018-f1653af2a577,3\"",
      "createdDateTime": "2018-08-25T22:47:30Z",
      "eTag": "\"00024848-0d4e-4ee8-b018-f1653af2a577,3\"",
      "id": "11",
      "lastModifiedDateTime": "2018-08-25T22:47:30Z",
      "webUrl": "https://XXXXX.sharepoint.com/sites/GeneratorApp/Lists/GenApp/11_.000",
      "createdBy": {
        "user": {
          "email": "XXXXX@XXXXX.com",
          "id": "b0465821-e891-4f44-9e18-27e875f1b75d",
          "displayName": "XXXXX"
        }
      },
      "lastModifiedBy": {
        "user": {
          "email": "XXXXX@XXXXX.com",
          "id": "b0465821-e891-4f44-9e18-27e875f1b75d",
          "displayName": "XXXXX"
        }
      },
      "parentReference": {},
      "contentType": {
        "id": "0x0100E19591A4ECA81542AEA41A6AAFED6781"
      },
      "fields@odata.context": "https://graph.microsoft.com/v1.0/$metadata#sites('XXXXX.sharepoint.com%2C495435b4-60c3-49b7-8f6e-1d262a120ae5%2C0fad9f67-35a8-4c0b-892e-113084058c0a')/lists('18a725ac-83ef-48fb-a5cb-950ca2378fd0')/items('11')/fields/$entity",
      "fields": {
        "@odata.etag": "\"00024848-0d4e-4ee8-b018-f1653af2a577,3\"",
        "SerialNumber": "20180824-1438-DC6-Generator-R",
        "id": "11"
      }
    },
    {
      "@odata.etag": "\"7c8e80ed-6fea-408a-9594-2b7b13e3691b,3\"",
      "createdDateTime": "2018-08-25T23:02:43Z",
      "eTag": "\"7c8e80ed-6fea-408a-9594-2b7b13e3691b,3\"",
      "id": "12",
      "lastModifiedDateTime": "2018-08-25T23:02:43Z",
      "webUrl": "https://XXXXX.sharepoint.com/sites/GeneratorApp/Lists/GenApp/12_.000",
      "createdBy": {
        "user": {
          "email": "XXXXX@XXXXX.com",
          "id": "b0465821-e891-4f44-9e18-27e875f1b75d",
          "displayName": "XXXXX"
        }
      },
      "lastModifiedBy": {
        "user": {
          "email": "XXXXX@XXXXX.com",
          "id": "b0465821-e891-4f44-9e18-27e875f1b75d",
          "displayName": "XXXXX"
        }
      },
      "parentReference": {},
      "contentType": {
        "id": "0x0100E19591A4ECA81542AEA41A6AAFED6781"
      },
      "fields@odata.context": "https://graph.microsoft.com/v1.0/$metadata#sites('XXXXX.sharepoint.com%2C495435b4-60c3-49b7-8f6e-1d262a120ae5%2C0fad9f67-35a8-4c0b-892e-113084058c0a')/lists('18a725ac-83ef-48fb-a5cb-950ca2378fd0')/items('12')/fields/$entity",
      "fields": {
        "@odata.etag": "\"7c8e80ed-6fea-408a-9594-2b7b13e3691b,3\"",
        "SerialNumber": "20180824-1456-DC6-Generator-C",
        "id": "12"
      }
    }
  ]
}}

What I ultimately want to do is create a dropdown that is populated with the SerialNumber. 我最终想要做的是创建一个填充了SerialNumber的下拉列表。 When the SerialNumber is selected in the dropdown, it will return the id so that I can then plug that into a GET request to retrieve the appropriate listitems. 当在下拉列表中选择SerialNumber时,它将返回id,以便我可以将其插入GET请求以检索适当的列表项。

I am trying to figure out if I need to do a foreach to create a LIST<> or something else all together. 我想弄清楚我是否需​​要做一个foreach来创建LIST <>或其他所有东西。

I do have this class setup, but wasn't sure if I could use it the way I thought I could. 我确实有这个类设置,但不确定我是否可以按照我认为的方式使用它。

public class Lookup
{
    string id { get; set; };
    string SerialNumber { get; set; }
}

This is the final working code: 这是最终的工作代码:

    private async void GetButton_Click(object sender, RoutedEventArgs e)
    {
        var (authResult, message) = await Authentication.AquireTokenAsync();
        ResultText.Text = message;

        if (authResult != null)
        {
            var httpClient = new HttpClient();
            HttpResponseMessage response;
            var request = new HttpRequestMessage(HttpMethod.Get, geturl);
            //Add the token in Authorization header
            request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", authResult.AccessToken);
            response = await httpClient.SendAsync(request);
            var content = await response.Content.ReadAsStringAsync();
            JObject json = JObject.Parse(content);
            var result = JsonConvert.DeserializeObject<SharePointListItems.RootObject>(content);
            foreach (var d in result.value)
            {
                Lookups.Add(new SharePointListItems.Lookup() { id = d.fields.id, SerialNumber = d.fields.SerialNumber });
            }
            TestComboBox.ItemsSource = Lookups;
        }
    }

    private void TestComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        if (TestComboBox.SelectedIndex != -1)
        {
            var mylookupId = (TestComboBox.SelectedItem as SharePointListItems.Lookup).id;// get your id and do further processing here.
            ResultText.Text = mylookupId;
        }
    }

public class SharePointListItems
{
    public class Lookup
    {
        public string SerialNumber { get; set; }
        public string id { get; set; }
        public override string ToString()
        {
            return SerialNumber;
        }
    }

    public class Value
    {
        public Lookup fields { get; set; }
    }

    public class Fields
    {
        [JsonProperty("@odata.etag")]
        public string ODataETag { get; set; }

        ...
    }

    public class RootObject
    {
        [JsonProperty("@odata.context")]
        public string ODataContext { get; set; }

        [JsonProperty("@odata.etag")]
        public string ODataETag { get; set; }

        [JsonProperty("fields@odata.context")]
        public string FieldsODataContext { get; set; }

        public Fields Fields { get; set; }

        public List<Value> value { get; set; }
    }    
}

There are two way can create model easily. 有两种方法可以轻松创建模型。

  1. You can use Web Essentials in Visual Studio, use Edit > Paste special > paste JSON as class, you can easier to know the relation between Json and model. 您可以在Visual Studio中使用Web Essentials,使用编辑>粘贴特殊>粘贴JSON作为类,您可以更容易地了解Json和模型之间的关系。

  2. If you can't use Web Essentials you can instead of use http://json2csharp.com/ online JSON to Model class. 如果您无法使用Web Essentials,则可以使用http://json2csharp.com/在线JSON到Model类。

You can try to use those models to carry your JSON Format. 您可以尝试使用这些模型来携带JSON格式。

public class Lookup
{
    public string SerialNumber { get; set; }
    public string id { get; set; }
}

public class Value
{
    public Lookup fields { get; set; }
}

public class RootObject
{
    public List<Value> value { get; set; }
}

Then you can use obj.value property collection directly. 然后你可以直接使用obj.value属性集合。

var obj = JsonConvert.DeserializeObject<RootObject>(jsonData);
foreach (var item in obj.value)
{
    //item.fields.id
    //item.fields.SerialNumber
}

A good example of how to bind a list of data to Combobox ( dropdown ) is here : https://www.c-sharpcorner.com/article/data-binding-in-xaml-uwp-using-combobox/ 下面是一个如何将数据列表绑定到Combobox (下拉列表)的一个很好的例子: https//www.c-sharpcorner.com/article/data-binding-in-xaml-uwp-using-combobox/

in this example the class is a Student with id and Name and it shows how u can show the name in combobox. 在此示例中,类是具有idNameStudent ,它显示了如何在组合框中显示名称。

I will modify it a little for your scenario but if you want to go in depth than you can visit the provided link above. 我将根据您的情况对其进行一些修改,但如果您想深入了解,请访问上面提供的链接。

This is the class 这是班级

public class Fields
{
    public string SerialNumber { get; set; }
    public string id { get; set; }
    public override string ToString() 
    {  
        return this.SerialNumber; // so that we can just bind to the object and get serial number in the ui. 
    }
}  

Backend for adding items to the List 用于向List添加项目的后端

public sealed partial class MainPage: Page 
{  
    List<Lookup> Lookups = new List<Lookup>();  
    public MainPage() 
    {  
        this.InitializeComponent();  
        Lookups.Add(new Lookup() {id = 1, SerialNumber = "S1"});  
        Lookups.Add(new Lookup() {id = 2, SerialNumber = "S2"}); 
        Lookups.Add(new Lookup() {id = 3, SerialNumber = "S3"});  
        Lookups.Add(new Lookup() {id = 4, SerialNumber = "S4"}); 
        //add as many items here as u want, u can even use a for loop or foreach loop or a Deserializer with newsoft json to get objects from ur json like below.
        //var data = JsonConvert.DeserializeObject<RootObject>(jsonData);
        //foreach (var d in data.value)
        //{
        //    //d.fields.id //this is how u can get the inside properties.
        //}
        yourComboBox.ItemSource = Lookups;//setting item source to UI.
    } 
}

after you successfully bind the data with UI you can use SelectionChanged event of your combobox to do further logic as you require, 在使用UI成功绑定数据后,您可以使用组合框的SelectionChanged事件根据需要执行进一步的逻辑,

void MyComboBox_SelectionChanged(object sender, object args)
{
    if(MyCombobox.SelectedIndex!=-1)
    {
        var mylookupId = (MyCombobox.SelectedItem as Lookup).id;// get your id and do further processing here.
    }
}

I think this will be easy when using newtonsoft : 我认为使用newtonsoft时这很容易:

var dynamicObject = JObject.Parse(yourstring);
var list = new List<Lookup>();
//now you have a dynamic object containing an array.
//this should be doable with linq as well.
//note, the type is dynamic
foreach (dynamic thing in dynamicObject )
{
   list.Add(new Lookup()
   {
      id = thing.fields.id,
      SerialNumber = thing.fields.SerialNumber
   });
}

disclaimer: not tested in any way ;-) 免责声明:未经任何方式测试;-)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM