abhinavm93
abhinavm93

Reputation: 152

How do i hard code JSON for my given class to store in database

using System;
using SQLite;

namespace Students
{
public class Student
{
    public Student()
    {
    }

    [PrimaryKey, AutoIncrement]
    public int ID { get; set; }

    public string Name { get; set; }

    public string percent { get; set; }

    public string rollNo { get; set; }

}
}

This is my SQLite database class that i use to instantiate objects of type Students. What i want now is really simple, A simple hardcoded JSON object declared in C# ,Serialized ,which i can store to this database after deserialising it(Just to test and see if it's working)

My sample JSON which im trying to get stored in the database is :

[
  {
    "name": "Gopi",
    "rollNo": "13",
    "%age": "33"
  },
  {
    "name": "Topi",
    "rollNo": "23",
    "%age": "43"
  },
  {
   "name": "Kopi",
   "rollNo": "33",
   "%age": "53"
   }
]

I want to store these values into my SQLite database after parsing this JSON object in C#. Im not sure how to proceed.

Upvotes: 0

Views: 1449

Answers (1)

Antoine
Antoine

Reputation: 312

Create some handling class like:

public class Handler{
public string name { get; set; }
public string rollNo { get; set; }
public string age { get; set; }}

And then:

public static HttpClient CreateClient()
    {
        var httpClient = new HttpClient
        {
            BaseAddress = new Uri(someURL)
        };

        httpClient.DefaultRequestHeaders.Accept.Clear();
        httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

        return httpClient;
    }

public static async Task<string> Get(string path)
{
    using (var client = CreateClient())
    {
        var getResponse = await client.GetAsync(path);
        return await getResponse.Content.ReadAsStringAsync();

    }
} 



public async Task<string> UpdateFriendsLocation()
    {
        var response = await WebServices.Get(someURL);
        return response;
    }

//In the place you want
var resp = JsonConvert.DeserializeObject<Handler>(response);

With this in your handler you have the data and then you have to make the inputs in your SQLite from that data.

Upvotes: 1

Related Questions