My model is GasStation.
using Newtonsoft.Json;
using SQLite;
using System;
using System.Collections.Generic;
using System.Text;
namespace TDEv2.Models
{
public class GasStation
{
[JsonProperty("costcentre")][PrimaryKey]
public string CostCentre { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("id")]
public string Id { get; set; }
}
}
My GasStationQuery contains this:
namespace TDEv2.Models
{
public class GasStationQuery
{
public GasStation[] GasStations { get; set; }
}
}
My JSON Array looks like this:
gasstations: [
{
"id": 01,
"name": "GasStation1",
"costcentre": 123
},
{
"id": 02,
"name": "GasStation2",
"costcentre": 456
}
]
Now I want to deserialize this into my SQLite database:
using SQLite;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using TDEv2.Models;
namespace TDEv2.Data
{
public class GasStationDatabase
{
readonly SQLiteAsyncConnection database;
public GasStationDatabase(string dbPath)
{
database = new SQLiteAsyncConnection(dbPath);
database.CreateTableAsync<GasStation>().Wait();
}
public Task<List<GasStation>> GetItemsAsync()
{
return database.Table<GasStation>().ToListAsync();
}
public Task<GasStation> GetItemAsync(string costCentre)
{
return database.Table<GasStation>().Where(i => i.CostCentre == costCentre).FirstOrDefaultAsync();
}
public Task<int> SaveItemAsync(GasStation gasStation)
{
if (gasStation.CostCentre != null)
{
return database.UpdateAsync(gasStation);
}
else
{
return database.InsertAsync(gasStation);
}
}
}
}
Now I want to do an initial sync to fill my database to work with offline on the devices, but I don't know further steps since I am programming for not that long.
Here's my try to fill the database:
using System.Net;
using TDEv2.Data;
using TDEv2.Models;
namespace TDEv2.Services
{
public class InitialAsyncGasStationDatabase
{
private GasStationDatabase db;
public GasStationQuery InitialAsyncGasStationsToDatabase()
{
string json;
using (WebClient client = new WebClient())
{
json = client.DownloadString($"http://xxx/gasstations.json");
}
foreach (GasStation gasStation in json)
{
db.SaveItemAsync(gasStation);
}
return;
}
}
}
The code doesn't work. I am getting an error in the foreach section with Cannot convert type "char" to "TDEv2.Models.GasStation"
you need to deserialize your json into an object before you can save it to the db
using (WebClient client = new WebClient())
{
json = client.DownloadString($"http://xxx/gasstations.json");
}
// using newtonsoft json.net - use http://json2csharp.com/ to verfiy
// that your C# model class actually matches your json
var data = JsonConvert.DeserializeObject<GasStationQuery>(json);
foreach (GasStation gasStation in data.GasStations)
{
db.SaveItemAsync(gasStation);
}
Probably your source has a list of GasStations, so you can Deserialize your json object into a List of GasStation,
private GasStationDatabase db;
public GasStationQuery InitialAsyncGasStationsToDatabase()
{
string json;
using (WebClient client = new WebClient())
{
json = client.DownloadString($"http://xxx/gasstations.json");
}
var gasStationList = JsonConvert.DeserializeObject<List<GasStation>>(json);
foreach (GasStation gasStation in gasStationList )
{
db.SaveItemAsync(gasStation);
}
return;
}
Related
I am trying to fetch data from 000webhost server into my xamarin.android application. connection of php mysqldatabase is working good but I am getting JSONException in one of my classes shown below.
DataPhraser.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Java.Lang;
using Org.Json;
using Object = Java.Lang.Object;
using String = System.String;
namespace database_test.database.mySQL
{
class DataPhraser : AsyncTask
{
Context c;
private Spinner sp;
private String jsonData;
JavaList<string> Universities = new JavaList<string>();
private ProgressDialog pd;
public DataPhraser(Context c, Spinner sp, string jsonData)
{
this.c = c;
this.sp = sp;
this.jsonData = jsonData;
}
protected override void OnPreExecute()
{
base.OnPreExecute();
pd = new ProgressDialog(c);
pd.SetTitle("Parse Data");
pd.SetMessage("Parsing Data..... Please Wait");
pd.Show();
}
protected override Object DoInBackground(params Object[] #params)
{
//throw new NotImplementedException();
return this.ParseData();
}
protected override void OnPostExecute(Object result)
{
base.OnPostExecute(result);
pd.Dismiss();
if (Integer.ParseInt(result.ToString()) == 0)
{
Toast.MakeText(c, "unable to Prase", ToastLength.Short).Show();
}
else
{
ArrayAdapter<string> adapter = new ArrayAdapter<string>(c, Android.Resource.Layout.SimpleListItem1, Universities);
sp.Adapter = adapter;
sp.ItemSelected += sp_ItemSelected;
}
}
private void sp_ItemSelected(object sender, AdapterView.ItemSelectedEventArgs e)
{
Toast.MakeText(c, Universities[e.Position], ToastLength.Short).Show();
}
private int ParseData()
{
try
{
JSONArray ja = new JSONArray(jsonData);
JSONObject jo = null;
Universities.Clear();
for (int i = 0; i < ja.Length(); i++)
{
jo = ja.GetJSONObject(i);
String name = jo.GetString("Country");
Universities.Add(name);
}
return 1;
}
catch (System.Exception e)
{
Console.WriteLine(e);
}
return 0;
}
}
}
I am getting error at " JSONArray ja = new JSONArray(jsonData)" this point of the code.
Mysqldatabase is
According to your gson, you can try to use Newtonsoft.Json Nuget ,for example:
namespace QuickType
{
using System;
using System.Collections.Generic;
using System.Globalization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
public partial class Welcome
{
[JsonProperty("Options")]
public Option[] Options { get; set; }
}
public partial class Option
{
[JsonProperty("ID")]
public long Id { get; set; }
[JsonProperty("University Name")]
public string UniversityName { get; set; }
[JsonProperty("Country")]
public string Country { get; set; }
[JsonProperty("Course")]
public string Course { get; set; }
[JsonProperty("Field of Study")]
public string FieldOfStudy { get; set; }
[JsonProperty("Course Language")]
public string CourseLanguage { get; set; }
[JsonProperty("Type of Institution")]
public string TypeOfInstitution { get; set; }
}
public partial class Welcome
{
public static Welcome FromJson(string json) => JsonConvert.DeserializeObject<Welcome>(json, QuickType.Converter.Settings);
}
public static class Serialize
{
public static string ToJson(this Welcome self) => JsonConvert.SerializeObject(self, QuickType.Converter.Settings);
}
internal static class Converter
{
public static readonly JsonSerializerSettings Settings = new JsonSerializerSettings
{
MetadataPropertyHandling = MetadataPropertyHandling.Ignore,
DateParseHandling = DateParseHandling.None,
Converters =
{
new IsoDateTimeConverter { DateTimeStyles =
DateTimeStyles.AssumeUniversal }
},
};
}
}
For more details, you can check: https://app.quicktype.io/#l=cs&r=json2csharp
Note: you can just copy your json string to the left part of above link, then it will convert the json into relative data models.
I am trying to stream a large JSON file and deserialize item by item during the streaming.
I am using for this test https://github.com/ysharplanguage/FastJsonParser/blob/master/JsonTest/TestData/fathers.json.txt.
This is my code:
using Newtonsoft.Json;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Newtonsoft.Json.Linq;
using System.Threading.Tasks;
namespace AMServices.Controllers
{
public class FathersData
{
public Father[] fathers { get; set; }
}
public class Someone
{
public string name { get; set; }
}
public class Father : Someone
{
public int id { get; set; }
public bool married { get; set; }
// Lists...
public List<Son> sons { get; set; }
// ... or arrays for collections, that's fine:
public Daughter[] daughters { get; set; }
}
public class Child : Someone
{
public int age { get; set; }
}
public class Son : Child
{
}
public class Daughter : Child
{
public string maidenName { get; set; }
}
public class StreamerController : ApiController
{
static readonly JsonSerializer _serializer = new JsonSerializer();
static readonly HttpClient _client = new HttpClient();
[HttpPost]
[Route("streamer/stream")]
public async Task<IHttpActionResult> stream()
{
string apiUrl = "https://github.com/ysharplanguage/FastJsonParser/blob/master/JsonTest/TestData/fathers.json.txt";
using (var stream = await _client.GetStreamAsync(apiUrl).ConfigureAwait(false))
using (var reader = new StreamReader(stream))
using (var json = new JsonTextReader(reader))
{
if (json == null)
StatusCode(HttpStatusCode.InternalServerError);
JsonSerializer serializer = new JsonSerializer();
JObject obj = JObject.Load(json);
// Father f = serializer.Deserialize<Father>(json);
}
return StatusCode(HttpStatusCode.OK);
}
}
}
When i call this WebAPI Controller Method from Postman i get the following error
"ExceptionMessage": "Unexpected character encountered while parsing value: <. Path '', line 0, position 0.",
"ExceptionType": "Newtonsoft.Json.JsonReaderException",
What is wrong with this code?
You are trying to parse an html page.
Try with the raw version :
https://raw.githubusercontent.com/ysharplanguage/FastJsonParser/master/JsonTest/TestData/fathers.json.txt
I am currently trying to implement MessagePack in a solution which contains 2 projects : AspNet Core WebAPI and a simple console app. The following package was added :
How fo I Deserialize the object back on the client, here is the code snippets, also when Posting back an object from the client to the api, do I just Serialize on the client and send it to the Post method in the api, which will take a string, take the string and Deserialize it again, I will need to pass the type somehow to the controller also.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using MessagePack;
using Microsoft.AspNetCore.Mvc;
namespace WebApplication1.Controllers
{
[Route("api/[controller]")]
public class ValuesController : Controller
{
[HttpGet]
public IActionResult Get()
{
var results = new List<Superhero>();
results.Add(new Superhero { HeroID = 1, HeroName = "Bruce Wayne" });
results.Add(new Superhero { HeroID = 2, HeroName = "Selina Kyle" });
results.Add(new Superhero { HeroID = 3, HeroName = "Clark Kent" });
var bytes = MessagePackSerializer.Serialize(results);
return Ok(bytes);
}
[HttpGet("{id}")]
public string Get(int id)
{
return "value";
}
[HttpPost]
public void Post([FromBody]string value)
{
// how to I Deserialize here ? what do I just post from client to
// with the Serialized object and pass the type also ???
}
[HttpPut("{id}")]
public void Put(int id, [FromBody]string value)
{
}
[HttpDelete("{id}")]
public void Delete(int id)
{
}
}
[MessagePackObject]
public class Superhero
{
[Key(0)]
public int HeroID { get; set; }
[Key(1)]
public string HeroName { get; set; }
}
}
using MessagePack;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
namespace MessagePackExampleOne
{
class Program
{
static HttpClient client = new HttpClient();
static void Main(string[] args)
{
client.BaseAddress = new Uri("http://localhost:57752");
client.DefaultRequestHeaders.Accept.Clear();
HttpResponseMessage response = client.GetAsync("/api/values").Result;
if (response.IsSuccessStatusCode)
{
var result = response.Content.ReadAsStringAsync().Result;
//how to Deserialize this objec ??
// Console.WriteLine(MessagePackSerializer.ToJson(result));
// var mc2 = MessagePackSerializer.Deserialize<List<Superhero>>(result);
}
Console.Read();
}
}
[MessagePackObject]
public class Superhero
{
[Key(0)]
public int HeroID { get; set; }
[Key(1)]
public string HeroName { get; set; }
}
}
to send something in post method from client use TryAddWithoutValidation:
var x = MessagePackSerializer.Serialize(MyCLassObj to send);
var content = new ByteArrayContent(x);
content.Headers.TryAddWithoutValidation("Content-Type", "application/x-msgpack");
httpResponse = await httpClient.PostAsync("/api...", content,token);
I am try to read data from this JSON file http://www.astro-phys.com/api/de406/states?date=1000-1-20&bodies=mars the date reads fine but I want to read :
[-168045229.22750974, 164411532.90034229, 80245103.265201837]
But as the data doesn't have a name I don't know how. This is my current code
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Web.Script.Serialization;
using System.Windows.Forms;
namespace Planets
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void pictureBox1_Click(object sender, EventArgs e)
{
}
private void Form1_Load(object sender, EventArgs e)
{
string filecontents;
string pagerequest = "http://www.astro-phys.com/api/de406/states?date=1000-1-20&bodies=mars";
WebRequest request = WebRequest.Create(#pagerequest);
WebResponse response = request.GetResponse();
Stream data = response.GetResponseStream();
string html = string.Empty;
using (StreamReader sr = new StreamReader(data))
{
filecontents = sr.ReadToEnd();
}
JavaScriptSerializer jsonSerialiser = new JavaScriptSerializer();
Results results = jsonSerialiser.Deserialize<Results>(filecontents);
richTextBox1.Text = (results.date);
Console.Write(results.date);
Console.ReadLine();
}
}
public class Results
{
public string date { get; set; }
public Position position { get; set; }
}
//public class Position
//{
// public int x { get; set; }
// public int y { get; set; }
//}
}
I am brand new to this and any help would be appreciated
Thanks
Your Results class should look something like this
public class Results
{
public string date { get; set; }
public IDictionary<string, IList<decimal[]>> results { get; set; }
public string unit { get; set; }
}
This allows for multiple planetary data points to be defined in the JSON.
i.e. if you were to call http://www.astro-phys.com/api/de406/states?date=1000-1-20&bodies=mars,earth would return mars and earth etc.
Then to access a specific co-ordinates
var coord1 = results.results["mars"][0][0]; // -168045229.22750974
var coord2 = results.results["mars"][0][1]; // 164411532.90034229
var coord3 = results.results["mars"][0][2]; // 80245103.265201837
i created a json file on my server which im using to send data to a c# program through JSON.NET deserialize. However im im getting a null object exception, can anyone please show me how to create the classes. Thanks
My class is here
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Newtonsoft.Json;
namespace WindowsFormsApplication4
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
Load();
}
public void Load()
{
label1.Text = "State:\nLoading...";
try
{
Products pd = new Products();
using (var webClient = new System.Net.WebClient())
{
// download json from url
var json = webClient.DownloadString(url);
// Now parse with JSON.Net
Products convert = JsonConvert.DeserializeObject<Products>(json) as Products;
label1.Text += pd.info.ToString();
label1.Text += "\nWeb Service Connected To";
}
}
catch (JsonSerializationException jsonerr) { label1.Text += "\nWeb Service Connection Failed"; MessageBox.Show(jsonerr.ToString()); }
catch (Exception err) { throw; }
finally { label1.Text += "\nWeb Service Closed"; }
}
}
}
public class Products
{
public Info info;
[JsonProperty("post")]
public Info infos
{
get { return info; }
set { info = value; }
}
}
public class Info
{
private string pd_name;
private int pd_id;
[JsonProperty("pd_id")]
public int pd_ids
{
get { return pd_id; }
set { pd_id = value; }
}
[JsonProperty("pd_name")]
public string pd_names
{
get { return pd_name; }
set { pd_name = value; }
}
}
You're not handling the posts value in the JSON. So if your JSON is formatted like this:
{ "posts" : [ { "post" : { "pd_id" : "399",
"pd_name" : "1.2mm Cylinder Labret"} },
{ "post" : { "pd_id" : "415",
"pd_name" : "1.2mm Laser Etched Labret" }}
] }
Try setting up your classes like this:
public class Posts
{
public List<Products> posts { get; set; }
}
public class Products
{
public List<Info> post { get; set; }
}
public class Info
{
public string pd_id { get; set; }
public string pd_name {get; set; }
}