简体   繁体   中英

make streamreader json file to object c#

I have code that makes an API call to a URL. Now i am stuck I need to get the JSON response written into T-SQL. I believe I will have to parse the response into C# objects.

The response contains information contained in my class lastKnownPosition.

using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace apicall
{
public class Program
{
    public static void Main(string[] args)
    {
        WebRequest request = WebRequest.Create("https://xxx/ion.json");
        request.Method = "GET";
        request.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes("xxxxx:xxxxxx"));
        HttpWebResponse response = (HttpWebResponse)request.GetResponse();
        Console.WriteLine(response.StatusDescription);
        Stream dataStream = response.GetResponseStream();
        // Open the stream using a StreamReader for easy access.
        StreamReader reader = new StreamReader(dataStream);

        // Read the content.            
        string responseFromServer = reader.ReadToEnd();            

        var myUser = JsonConvert.DeserializeObject(responseFromServer);

        // Display the content.
        //Console.WriteLine(responseFromServer);
        Console.WriteLine(myUser);
        // Cleanup the streams and the response.
        reader.Close();
        dataStream.Close();
        response.Close();
        Console.ReadLine();
    }
}

class lastKnownPosition
{
    public string Desription { get; set; }
    public string UnitId { get; set; }
    public DateTime Localtimestamp { get; set; }
    public float latitude { get; set; }
    public float longitude { get; set; }
    public string id { get; set; }
}   
}

to parse to an specific object you have to set which object do you want, try next:

var myUser = JsonConvert.DeserializeObject<lastKnownPosition>(responseFromServer);

edit, if contains more than one

var myUserList = JsonConvert.DeserializeObject<list<lastKnownPosition>>(responseFromServer);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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