Cannot deserialize - JSON.NET - Xamarin - json

I'm struggling with below message. Other JSON objects in the same app work correctly.
Newtonsoft.Json.JsonSerializationException: Cannot deserialize the current JSON array
(e.g. [1,2,3]) into type 'Monkeys.Models.Rootobject' because the type requires a JSON
object (e.g. {"name":"value"}) to deserialize correctly.
I have the following output from the API via web browser:
[{"Id":"1","Name":"Monkey 1","Location":null,"Details":null,"SKU":null,"Size":null,
"Color":null,"Image":null,"Brand":null,"NameSort":"M"},{"Id":"2","Name":"Monkey 2",
"Location":null, "Details":null,"SKU":null,"Size":null,"Color":null,"Image":null,
"Brand":null,"NameSort":"M"}]
The Model in my App:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
namespace Monkeys.Models
{
public class Monkey
{
public string Id { get; set; }
public string Name {get;set;}
public string Location { get; set; }
public string Details { get; set; }
//URL for our monkey image!
public string SKU { get; set; }
public string Size { get; set; }
public string Color { get; set; }
public string Image { get; set; }
public string Brand { get; set; }
public string NameSort
{
get
{
if (string.IsNullOrWhiteSpace(Name) || Name.Length == 0)
return "?";
return Name[0].ToString().ToUpper();
}
}
}
public class Rootobject
{
public Monkey[] monkeys { get; set; }
}
}
The App:
using System;
using System.Net;
using Newtonsoft.Json;
using System.Threading.Tasks;
using Monkeys.Models;
using System.Collections.Generic;
namespace Monkeys.Apis
{
public class GetMonkeys
{
public GetMonkeys()
{
}
public async Task<Monkey[]> GetMonkeysAsync()
{
var client = new System.Net.Http.HttpClient();
client.BaseAddress =
new Uri("https://microsoft- apiappce13ac35390d40a684dd6ab72a9eef8f.azurewebsites.net:443/");
var response = await client.GetAsync("api/Monkey");
var earthquakesJson = response.Content.ReadAsStringAsync().Result;
var rootobject = JsonConvert.DeserializeObject<Rootobject> (earthquakesJson);
return rootobject.monkeys;
}
}
}

Your json data is an array of Monkey. Try this
// monkeys will be a List<Monkey>
var monkeys = JsonConvert.DeserializeObject<List<Monkey>>(earthquakesJson);

Related

System.Text.Json.Deserialize an array into C# class

First off, I am working with the Google recaptcha RESTful service trying to get the JSON object into a class. With WSDL's, Visual Studio will generate all this code for you so that it is easy to work with, but RESTful it seems you have to do everything yourself, am I missing something? I am working with VS2019 and would have thought there is some way to import this stuff to make life easy. I have yet to find anything, so...
Google is returning:
{
"success": false,
"error-codes": [
"invalid-input-response",
"invalid-input-secret"
]
}
I would like to deserialize it into this:
[DataContract]
public class GoogleReCaptchaResponse
{
[DataMember(Name = "success")]
public bool Success { get; set; }
[DataMember(Name = "error-codes")]
public List<string> ErrorCodes { get; set; }
[JsonExtensionData]
public Dictionary<string, object> ExtensionData { get; set; }
}
I see the error-codes in the ExtensionData, but ErrorCodes is always null. What do I have wrong?
https://dotnetfiddle.net/RtjbwR
You should use JsonPropertyName attribute from System.Text.Json.Serialization namespace
using System;
using System.Collections.Generic;
using System.Text.Json.Serialization;
public class GoogleReCaptchaResponse
{
[JsonPropertyName("success")]
public bool Success { get; set; }
[JsonPropertyName("error-codes")]
public List<string> ErrorCodes { get; set; }
}
public class Program
{
public static void Main()
{
GoogleReCaptchaResponse json = System.Text.Json.JsonSerializer.Deserialize<GoogleReCaptchaResponse>("{ \"success\": false, \"error-codes\": [\"invalid-input-response\",\"invalid-input-secret\"]}");
if (json.ErrorCodes == null)
{
Console.WriteLine("no Error Codes");
}
else
{
Console.WriteLine("Error Codes!");
}
}
}

Deserialize JSON data in to a class in c#

hello people I have this Json data:
https://openexchangerates.org/api/latest.json?app_id=6cf59607a32d408eb3e04de1427a3169
and I want to deserialize in the following class
using Newtonsoft.Json;
using System.Collections.Generic;
namespace Divisas2MVVM2.Classes
{
public class ExchangeRates
{
[JsonProperty(PropertyName = "disclaimer")]
public string Disclaimer { get; set; }
[JsonProperty(PropertyName = "license")]
public string License { get; set; }
[JsonProperty(PropertyName = "timestamp")]
public int TimeStamp { get; set; }
[JsonProperty(PropertyName = "base")]
public string Base { get; set; }
[JsonProperty(PropertyName = "rates")]
public Rates Rates { get; set; }
}
public class Rates
{
public double AED { get; set; }
public double AFN { get; set; }
public double ALL { get; set; }
public double AMD { get; set; }
// I cut the text so that it would not be to long
public double ZMW { get; set; }
public double ZWL { get; set; }
}
public class Rate
{
public double TaxRate { get; set; }
public string Code { get; set; }
}
this is my attribute
private ExchangeRates exchangeRates;
the constructor of my MainViewModel
new ObservableCollection data
Rates = new ObservableCollection<Rate>();
and in this method a get the json data
try
{
var client = new HttpClient();
client.BaseAddress = new Uri("https://openexchangerates.org");
var url = "/api/latest.json?app_id=6cf59607a32d408eb3e04de1427a3169";
var response = await client.GetAsync(url);
if (!response.IsSuccessStatusCode)
{
Message = response.StatusCode.ToString();
IsRunning = false;
return;
}
var result = await response.Content.ReadAsStringAsync();
exchangeRates = JsonConvert.DeserializeObject<ExchangeRates>(result);
}
everything works fine, the variable result has correctly the json data in a string format, but when i call JsonConvert . DeserializeObject, the data "rates" it is not assigned correctly, all the other data: disclaimer", "license", "timestamp" etc. is correctly assigned. only rates fail.
the string is correct
other data is correct in the class
rates is incorrect
sorry for my English I hope you have understood me :)
use this as your model class
namespace Rate
{
using System;
using System.Collections.Generic;
using System.Globalization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
public partial class Rates
{
[JsonProperty("disclaimer")]
public string Disclaimer { get; set; }
[JsonProperty("license")]
public string License { get; set; }
[JsonProperty("timestamp")]
public long Timestamp { get; set; }
[JsonProperty("base")]
public string Base { get; set; }
[JsonProperty("rates")]
public Dictionary<string, double> RatesRates { get; set; }
}
public partial class Rates
{
public static Rates FromJson(string json) => JsonConvert.DeserializeObject<Rates>(json, Rate.Converter.Settings);
}
public static class Serialize
{
public static string ToJson(this Rates self) => JsonConvert.SerializeObject(self, Rate.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 }
},
};
}
}
Then do this in your class
var data = Rate.Rates.FromJson("jsonresult");
var rate = data.RatesRates;
foreach (var pair in rate)
{
string symbol = pair.Key; //"AED"
double value = pair.Value; //3.673175,
}
var time = data.Timestamp;
var disclaimer = data.Disclaimer;
var license = data.License;
Tested and working

deserialize dataset in xamarin forms

How can you decrypt/ deserialize dataset. here is what i am getting from the web service. I am new to xamarin forms. Thanks in advance. i tried this json2csharp.com to convert, but got an error because it can convert datatable to csharp but not datasets.
[
[
{
"bit_HasError":false,
"vchar_ErrorMsg":""
}
],
[
{
"int_SurveyQuestionID":1,
"vchar_Description":"we",
"vchar_Instruction":"Question Instruction",
"int_AnswerType":1
},
{
"int_SurveyQuestionID":5,
"vchar_Description":"this is the question 2",
"vchar_Instruction":null,
"int_AnswerType":2
}
],
[
{
"int_SurveyQuestionID":1,
"vchar_Option":"option1"
},
{
"int_SurveyQuestionID":5,
"vchar_Option":"answer1"
},
{
"int_SurveyQuestionID":5,
"vchar_Option":"answer2"
},
{
"int_SurveyQuestionID":5,
"vchar_Option":"answer3"
},
{
"int_SurveyQuestionID":1,
"vchar_Option":"optionn2"
}
]
]
Using https://app.quicktype.io/ it is quite easy to get started, just copy paste your json in there, here is the result:
// To parse this JSON data, add NuGet 'Newtonsoft.Json' then do:
//
// using QuickType;
//
// var prject = Prject.FromJson(jsonString);
namespace QuickType
{
using System;
using System.Collections.Generic;
using System.Globalization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
public partial class Prject
{
[JsonProperty("bit_HasError", NullValueHandling = NullValueHandling.Ignore)]
public bool? BitHasError { get; set; }
[JsonProperty("vchar_ErrorMsg", NullValueHandling = NullValueHandling.Ignore)]
public string VcharErrorMsg { get; set; }
[JsonProperty("int_SurveyQuestionID", NullValueHandling = NullValueHandling.Ignore)]
public long? IntSurveyQuestionId { get; set; }
[JsonProperty("vchar_Description", NullValueHandling = NullValueHandling.Ignore)]
public string VcharDescription { get; set; }
[JsonProperty("vchar_Instruction")]
public string VcharInstruction { get; set; }
[JsonProperty("int_AnswerType", NullValueHandling = NullValueHandling.Ignore)]
public long? IntAnswerType { get; set; }
[JsonProperty("vchar_Option", NullValueHandling = NullValueHandling.Ignore)]
public string VcharOption { get; set; }
}
public partial class Prject
{
public static List<List<Prject>> FromJson(string json) => JsonConvert.DeserializeObject<List<List<Prject>>>(json, QuickType.Converter.Settings);
}
public static class Serialize
{
public static string ToJson(this List<List<Prject>> 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 }
},
};
}
}
P.S.: Please note that you have to modify the class names.

WP8 No Such a table Sqlite

i m trying to develop windows phone application but i have a problem about sqlite. I couldn't connect database and app. I had error message like this "no such table: hastalik". If some 1 have any idea, please share. Thanks for your help.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using System.IO;
using Windows.Storage;
using SQLite;
namespace illnessTracker
{
public partial class Page1 : PhoneApplicationPage
{
public static string DB_PATH = Path.Combine(Path.Combine(ApplicationData.Current.LocalFolder.Path, "ilac.sqlite"));
public Page1()
{
InitializeComponent();
}
private void ApplicationBarIconButton_Click(object sender, EventArgs e)
{
using (SQLiteConnection dbConn = new SQLiteConnection("Data Source=ilac.sqlite; FailIfMissing=True"))
{
// Create a new task.
hastalik hasta = new hastalik();
hasta.hastalikAdi = txtbxHastalikAdi.Text;
hasta.semptomlar = txtbxSemptomlar.Text;
hasta.ilaclar = tbxIlaclar.Text;
hasta.not = tbxNot.Text;
hasta.doktorTavsiyesi = tbxTavsiye.Text;
hasta.tarihi = DateTime.Now.Date;
/// Insert the new task in the Task table.
dbConn.Insert(hasta);
}
}
[Table("hastalik")]
public class hastalik
{
[Column("hastalikID")]
[PrimaryKey, AutoIncrement]
public int hastalikID { get; set; }
[Column("hastalikAdi")]
public string hastalikAdi { get; set; }
[Column("semptomlar")]
public string semptomlar { get; set; }
[Column("ilaclar")]
public string ilaclar { get; set; }
[Column("doktorTavsiyesi")]
public string doktorTavsiyesi { get; set; }
[Column("not")]
public string not { get; set; }
[Column("tarihi")]
public DateTime tarihi { get; set; }
}
}
}

Deserializing Jarray in JSON.NET

i need to deserialize this.
{"previous_cursor_str":"0","next_cursor":0,"ids":[741999686,240455509,126524150,143548100,124328422,624776268,393738125,587829914,280834485,64818350,282713007,90425850,759794,164401208,114771958,114364910,89725893],"previous_cursor":0,"next_cursor_str":"0"}
any idea?
Its a JObject really with an array of Id's inside it.
First you can create a class to represent the json like this:
public class RootObject
{
public string previous_cursor_str { get; set; }
public int next_cursor { get; set; }
public List<int> ids { get; set; }
public int previous_cursor { get; set; }
public string next_cursor_str { get; set; }
}
Then to deserialize the json into the object you do this:
var myJsonObject = JsonConvert.DeserializeObject<RootObject>(jsonString);
Or if you just want the ids in a array:
var obj = JObject.Parse(jsonstring);
var idArray = obj["ids"].Children().Select(s=>s.value<string>());
Just tried https://jsonclassgenerator.codeplex.com/ and got the code below. Which is qhite the same as geepie's class. nice tool.
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace Example
{
class Result
{
[JsonProperty("previous_cursor_str")]
public string PreviousCursorStr { get; set; }
[JsonProperty("next_cursor")]
public int NextCursor { get; set; }
[JsonProperty("ids")]
public IList<int> Ids { get; set; }
[JsonProperty("previous_cursor")]
public int PreviousCursor { get; set; }
[JsonProperty("next_cursor_str")]
public string NextCursorStr { get; set; }
}
public static unsafe void Main()
{
Result result = JsonConvert.DeserializeObject<Result> (" ... your string ...");
Console.WriteLine(result);
}
}