How can i deserialize a local json file to an object?
I'm trying to deserialize a local json file in xamarin but it just doesn't work i read many guides and watched some tutorials but none of them helped and most of them give the same code i'm using right now
My code:
public test()
{
InitializeComponent();
List<Rootobject> ob = new List<Rootobject>();
var assembly = IntrospectionExtensions.GetTypeInfo(typeof(test)).Assembly;
Stream stream = assembly.GetManifestResourceStream($"TunisiaPrayer.states.json");
string text = "";
using (var reader = new StreamReader(stream))
{
text = reader.ReadToEnd();
}
ob = JsonConvert.DeserializeObject<List<Rootobject>>(text);
//printing the json file to make sure it read it fully
//i get no error here
DisplayJson.Text = text;
//try catch to test if it was deserialized or not
try
{
//printing a property of ob in a label element to see if it works
DisplayData.Text = ob[2].Property1.data.gouvernorat.intituleAn;
}
catch (Exception ex)
{
DisplayData.Text = ex.Message;
}
}
RootObject Class:
namespace TunisiaPrayer.Models
{
public class Rootobject
{
public Class1 Property1 { get; set; }
}
public class Class1
{
public Data data { get; set; }
}
public class Data
{
public Gouvernorat gouvernorat { get; set; }
public Delegation[] delegation { get; set; }
}
public class Gouvernorat
{
public int id { get; set; }
public string intituleAr { get; set; }
public string intituleAn { get; set; }
}
public class Delegation
{
public int id { get; set; }
public string intituleAr { get; set; }
public string intituleAn { get; set; }
}
}
sample of states.json:
[{
"data": {
"gouvernorat": {
"id": 358,
"intituleAr": "اريانة",
"intituleAn": "Ariana"
},
"delegation": [{
"id": 631,
"intituleAr": "اريانة",
"intituleAn": "Ariana"
},
{
"id": 534,
"intituleAr": "التظامن",
"intituleAn": "Attadhamon"
},
{
"id": 532,
"intituleAr": "سكرة",
"intituleAn": "Soukra"
}
]
}
},
{
"data": {
"gouvernorat": {
"id": 362,
"intituleAr": "القصرين",
"intituleAn": "Kasserine"
},
"delegation": [{
"id": 579,
"intituleAr": "العيون",
"intituleAn": "El Ayoun"
},
{
"id": 576,
"intituleAr": "سبيبة",
"intituleAn": "Sbiba"
},
{
"id": 575,
"intituleAr": "سبيطلة",
"intituleAn": "Sbitla"
},
{
"id": 573,
"intituleAr": "تالة",
"intituleAn": "Tala"
}
]
}
}]
error: Object reference not set to an instance of an object
note that when i print ob.Count it gives me the correct length of the list but i can't access any data in it
you have to use Root[] , not just root, try this
var obj =JsonConvert.DeserializeObject< List<Root>>(text);
test
var displayData = obj[1].data.gouvernorat.intituleAn; // = Kasserine
classes
public class Root
{
public Data data { get; set; }
}
public class Data
{
public Gouvernorat gouvernorat { get; set; }
public List<Delegation> delegation { get; set; }
}
public class Gouvernorat
{
public int id { get; set; }
public string intituleAr { get; set; }
public string intituleAn { get; set; }
}
public class Delegation
{
public int id { get; set; }
public string intituleAr { get; set; }
public string intituleAn { get; set; }
}
Related
Got the following structure given:
public class TaskList
{
public string Name { get; set; }
public List<ToDoTask> ToDoTasks { get; set; }
}
public class ToDoTask
{
public string Name { get; set; }
public string Note { get; set; }
public DateTime LastEdit { get; set; }
public bool Finished { get; set; }
}
I'm using System.Text.Json in .NET 5.0 to serialize a List successfully into a json-file:
JsonSerializerOptions serializeOptions = new() { WriteIndented = true };
string json = JsonSerializer.Serialize(taskLists, serializeOptions);
the result looks fine:
{
"TaskLists": [
{
"Name": "List1",
"ToDoTasks": [
{
"Name": "Task1",
"Note": "",
"LastEdit": "2022-04-19T13:05:10.0415588+02:00",
"Finished": false
},
{
"Name": "Task2",
"Note": "",
"LastEdit": "2022-04-19T13:05:13.9269202+02:00",
"Finished": false
}
]
},
{
"Name": "List2",
"ToDoTasks": [
{
"Name": "Task3",
"Note": "",
"LastEdit": "2022-04-19T13:05:18.3989081+02:00",
"Finished": false
},
{
"Name": "Task4",
"Note": "",
"LastEdit": "2022-04-19T13:05:23.0949034+02:00",
"Finished": false
}
]
}
]
}
When I deserialize this json-file, I only got the TaskLists but the ToDoTasks, are empty.
List<TaskList> taskLists = JsonSerializer.Deserialize<List<TaskList>>(json);
What do I have to do, get also the ToDoTask-Childs included into the deserialized objects?
Whenever you cannot figure out your model class, you can use Visual Studio's Edit - Paste Special - Paste JSON as Class to check out.
Your model classes should be like this:
public class Rootobject
{
public Tasklist[] TaskLists { get; set; }
}
public class Tasklist
{
public string Name { get; set; }
public Todotask[] ToDoTasks { get; set; }
}
public class Todotask
{
public string Name { get; set; }
public string Note { get; set; }
public DateTime LastEdit { get; set; }
public bool Finished { get; set; }
}
And you can Deserialize it:
static void Main(string[] args)
{
var query = JsonSerializer.Deserialize<Rootobject>(File.ReadAllText("data.json"));
}
Your json has a root object containing the task list, so List<TaskList> does not represent it correctly. Try:
public class Root
{
public List<TaskList> TaskLists { get; set; }
}
var root = JsonSerializer.Deserialize<Root>(json);
I'm trying to deserialize a JSON string into a C# object. When I trap in the debugger, the JSON visualizer appears to be parsing the string just fine. However, when I push the string through the following code, the object returned has null values for the properties.
Here's my code:
public static Item GetPrices(string itemStr)
{
Item item = JsonConvert.DeserializeObject<Item>(itemStr);
return item;
}
public class Item
{
[JsonProperty(PropertyName = "id")]
public string Id { get; set; }
[JsonProperty(PropertyName = "prices")]
public Prices Prices { get; set; }
}
public class Prices
{
[JsonProperty(PropertyName = "priceUofM")]
public PriceUofM[] PriceUofMs { get; set; }
}
public class PriceUofM
{
[JsonProperty(PropertyName = "uofm")]
public string UofM { get; set; }
[JsonProperty(PropertyName = "price")]
public string Price { get; set; }
}
and here's what I'm passing to it:
{
"item": {
"id": "1A50CC070S",
"prices":
[
{
"priceUofM": {
"uofm": "BOX",
"price": "$81.11"
}
},
{
"priceUofM": {
"uofm": "CASE",
"price": "$811.11"
}
}
]
}
}
I've run it through several online parsers, and all of them appear to be interpreting the JSON string just fine. What am I doing wrong in formatting the string to cause JsonConvert.DeserializeObject to fail?
Given this json:
{
"item": {
"id": "1A50CC070S",
"prices":
[
{
"priceUofM": {
"uofm": "BOX",
"price": "$81.11"
}
},
{
"priceUofM": {
"uofm": "CASE",
"price": "$811.11"
}
}
]
}
}
C# model would be:
public class Model
{
[JsonProperty("item")]
public Item Item { get; set; }
}
public class Item
{
[JsonProperty("id")]
public string Id { get; set; }
[JsonProperty("prices")]
public List<Price> Prices { get; set; }
}
public class Price
{
[JsonProperty("priceUofM")]
public PriceUofM PriceUofM { get; set; }
}
public class PriceUofM
{
[JsonProperty("uofm")]
public string UofM { get; set; }
[JsonProperty("price")]
public string Price { get; set; }
}
In order to deserialize the string into an Item object, JSON string would be something like:
{
"id": "1A50CC070S",
"prices":
[
{
"priceUofM": {
"uofm": "BOX",
"price": "$81.11"
}
},
{
"priceUofM": {
"uofm": "CASE",
"price": "$811.11"
}
}
]
}
Trying to get JSON data from ThingSpeak however getting the above error,
works well with JSON placeholder as the URL.
Here is my main cs code:
namespace Drip
{
public class Feed
{
public DateTime Created_at { get; set; }
public int Entry_id { get; set; }
public string Field1 { get; set; }
}
public partial class DripPage : TabbedPage
{
private const string Url = "https://thingspeak.com/channels/301726/field/1.json";
private HttpClient _client = new HttpClient();
private ObservableCollection<Feed> _data;
public DripPage()
{
InitializeComponent();
}
protected override async void OnAppearing()
{
var content = await _client.GetStringAsync(Url);
var data = JsonConvert.DeserializeObject<List<Feed>>(content);
_data = new ObservableCollection<Feed>(data);
postsListView.ItemsSource = _data;
base.OnAppearing();
}
Here is my JSON:
{
"channel": {
"id": 301726,
"name": "Testing ESP8266",
"description": "Water meter pulse count",
"latitude": "0.0",
"longitude": "0.0",
"field1": "Water Pulse",
"created_at": "2017-07-12T12:19:38Z",
"updated_at": "2017-09-26T08:41:17Z",
"elevation": "54",
"last_entry_id": 151
},
"feeds": [
{
"created_at": "2017-08-15T13:14:28Z",
"entry_id": 52,
"field1": "13.00\r\n\r\n"
},
{
"created_at": "2017-08-15T13:14:44Z",
"entry_id": 53,
"field1": "13.00\r\n\r\n"
},
{
"created_at": "2017-08-15T13:14:59Z",
"entry_id": 54,
"field1": "13.00\r\n\r\n"
}
]
}
The returned json is not an array, so it can't be deserialized as a List<Feed>, hence an exception is thrown. It is an object, and one of that object's members is the array that you are interested in. The backing C# class to deserialize should have the following members:
public class RootObject
{
public Channel channel { get; set; }
public List<Feed> feeds { get; set; }
}
public class Channel
{
public int id { get; set; }
public string name { get; set; }
public string description { get; set; }
public string latitude { get; set; }
public string longitude { get; set; }
public string field1 { get; set; }
public DateTime created_at { get; set; }
public DateTime updated_at { get; set; }
public string elevation { get; set; }
public int last_entry_id { get; set; }
}
public class Feed
{
public DateTime created_at { get; set; }
public int entry_id { get; set; }
public string field1 { get; set; }
}
Instead of deserializing to a List<Feed>, you would deserialize to a RootObject (or whatever you choose to call it):
var data = JsonConvert.DeserializeObject<RootObject>(content);
_data = new ObservableCollection<Feed>(data.feeds);
try this maybe it will work fine for you
first: place this code on your activity and instanciate all var;you will create a javalist to deserialize your json, then you will the method webclient to get your json, then you will use the method runonuithread to excute the process in background.
articles = new JavaList<RootObject>();
mWebClient = new WebClient();
mUrl = new Uri(urlAddress);
mWebClient.DownloadDataAsync("https://thingspeak.com/channels/301726/field/1.json");
mWebClient.DownloadDataCompleted += MWebClient_DownloadDataCompleted;
second: the method mWebClient.DownloadDataCompleted will generate this :
private void MWebClient_DownloadDataCompleted(object sender, DownloadDataCompletedEventArgs e)
{
RunOnUiThread(() =>
{
try
{
string json = Encoding.UTF8.GetString(e.Result);
articles = JsonConvert.DeserializeObject<JavaList<RootObject>>(json);
mAdapter = new ArticleAdapterCostum(this, articles);
mListView.Adapter = mAdapter;
}
catch (Exception exception)
{
Toast.MakeText(this, " Vueillez verifier votre connexion a internet puis reessayer ", ToastLength.Short).Show();
}
});
}
don't forget to create a costum adapter to your listview.
We have to do some changes in existing JSON response and it requires to modify existing c# code too. Till now I've tried but don't get the exact idea about the formatting as it is new for me.
Can any one please check and suggest the changes in below code?
Existing JSON message:
"hotel_room_types": {
"QUEEN": {
"code": "QUEEN",
"bed_type": {
"standard": [
5
],
"custom": []
},
"extra_bed_type": {
"standard": [
5
],
"custom": []
},
"accessibility": "compliant_with_local_laws_for_disabled",
"room_smoking_policy": "non_smoking"
}
}
In above JSON message we have to replace the "bed_type" and "extra_bed_type" with "bed_configurations" and "extra_bed_configurations" in below newly provided format by client:
"hotel_room_types": {
"QUEEN": {
"code": "QUEEN",
"bed_configurations": [
[{
"type": "standard",
"code": 3,
"count": 1
}],
[{
"type": "standard",
"code": 1,
"count": 2
}]
],
"extra_bed_configurations": [
[{
"type": "standard",
"code": 900302,
"count": 1
},
{
"type": "custom",
"name": "Rollaway with wheel locks and adjustable height",
"count": 1
}]
],
"accessibility": "compliant_with_local_laws_for_disabled",
"room_smoking_policy": "non_smoking"
}
}
Existing C# code to generate the JSON response message format:
public class HotelRoomType
{
public string code { get; set; }
public string name { get; set; }
public string description { get; set; }
public List<Photo> photos { get; set; }
public Amenities room_amenities { get; set; }
public string room_size { get; set; }
public string room_size_units { get; set; }
public BedType bed_type { get; set; }
public BedType extra_bed_type { get; set; }
public RoomViewType room_view_type { get; set; }
public string accessibility { get; set; }
public MaxOccupancy max_occupancy { get; set; }
public string room_smoking_policy { get; set; }
}
Below is the code to fill the data in required fields of JSON message its inside a method which contains lines of code so I get it separately:
HotelRoomType hotelrmtype = new HotelRoomType();
hotelrmtype.bed_type = Common.GetStandardBedTypeMappingID(rm.BedType);
if (rm.NumOfBed > 1)
hotelrmtype.extra_bed_type = hotelrmtype.bed_type; //same as bed type
hotelrmtypeDict.Add(rm.Code, hotelrmtype); //Binding Data into Dictionary.
GetStandardBedTypeMappingID() contains :
public static CRS.TripConnect.BedType GetStandardBedTypeMappingID(short code)
{
CRS.TripConnect.BedType tripConnectBedType = new CRS.TripConnect.BedType();
List<int> standardBedTypes = new List<int>();
List<object> customBedTypes = new List<object>();
tripConnectBedType.standard = standardBedTypes;
tripConnectBedType.custom = customBedTypes; //These is blank.
short id = 0;
switch (code)
{
case 10:
id = 3;
break;
case 20: // 20 Queen Q 5
id = 5;
break;
case 30: // 30 Double D 1
id = 1;
break;
case 40: // 40 Twin T 8
id = 8;
break;
}
standardBedTypes.Add(id);
return tripConnectBedType;
}
Update: With the help of #Sam Answer below I have modified the code:
public class HotelRoomType
{
//Added following properties
public List<List<Bed_Configurations>> bed_configurations { get; set; }
public List<List<Extra_Bed_Configurations>> extra_bed_configurations { get; set; }
}
Created two new classes as:
public class Bed_Configurations
{
public string type { get; set; }
public int code { get; set; }
public int count { get; set; }
}
public class Extra_Bed_Configurations
{
public string type { get; set; }
public int code { get; set; }
public int count { get; set; }
public string name { get; set; }
}
Now the question is: How to fill these two list?
I'm trying to achieve this like below but it is giving me conversion error.
Bed_Configurations bdConfig = new Bed_Configurations();
bdConfig.type = "Standard";
bdConfig.code = Common.GetStandardBedTypeMappingIDnew(rm.BedType);
bdConfig.count = rm.NumOfBed;
hotelrmtype.bed_configurations.Add(bdConfig);
Error Message:
Please Advise the changes in the above code so as to get the required JSON message. Appreciate your help!
public class RootClass
{
public HotelRoomType hotel_room_types { get; set; }
}
public class HotelRoomType
{
public BedModelAndDetails QUEEN { get;set; }
}
public class BedModelAndDetails
{
public string accessibility { get; set; }
public string room_smoking_policy { get; set; }
public string code { get; set; }
//public BedType bed_type { get; set; }
public object bed_type { get; set; }
//public BedType extra_bed_type { get; set; }
public object extra_bed_type { get; set; }
public List<List<BedConfiguration>> bed_configurations { get; set; }
public List<List<BedConfiguration>> extra_bed_configurations { get; set; }
}
public class BedType
{
public List<int> standard { get; set; }
public List<int> custom { get; set; }
}
public class BedConfiguration
{
public string type { get; set; }
public int code { get; set; }
public int count { get; set; }
}
[TestMethod]
public void ReplaceJson()
{
var inputJson1 = "{\"hotel_room_types\": {\"QUEEN\": {\"code\": \"QUEEN\", \"bed_type\": {\"standard\": [5],\"custom\": [] }, \"extra_bed_type\": { \"standard\": [5], \"custom\": [] },\"accessibility\": \"compliant_with_local_laws_for_disabled\", \"room_smoking_policy\": \"non_smoking\" } " +"}}";
var input1 = JsonConvert.DeserializeObject<RootClass>(inputJson1, new JsonSerializerSettings {NullValueHandling = NullValueHandling.Ignore});
var inputJson2 = "{\"hotel_room_types\": {\"QUEEN\": {\"code\": \"QUEEN\",\"bed_configurations\": [[{\"type\": \"standard\",\"code\": 3,\"count\": 1}],[{\"type\": \"standard\",\"code\": 1,\"count\": 2}]],\"extra_bed_configurations\": [[{\"type\": \"standard\",\"code\": 900302,\"count\": 1},{\"type\": \"custom\",\"name\": \"Rollaway with wheel locks and adjustable height\",\"count\": 1}]],\"accessibility\": \"compliant_with_local_laws_for_disabled\",\"room_smoking_policy\": \"non_smoking\"} }}";
var input2 = JsonConvert.DeserializeObject<RootClass>(inputJson2);
//var finalInput = new RootClass();
//finalInput.hotel_room_types = inputJson1
//input1.hotel_room_types.QUEEN.bed_configurations = input2.hotel_room_types.QUEEN.bed_configurations;
//input1.hotel_room_types.QUEEN.extra_bed_configurations = input2.hotel_room_types.QUEEN.extra_bed_configurations;
input1.hotel_room_types.QUEEN.bed_type = input2.hotel_room_types.QUEEN.bed_configurations;
input1.hotel_room_types.QUEEN.extra_bed_type = input2.hotel_room_types.QUEEN.extra_bed_configurations;
}
Does this help?
I am getting the json from zoho. I have a JSON like the following:
{
"response": {
"result": {
"Leads": {
"row": [
{
"no": "1",
"FL": [
{
"content": "1325469000000679001",
"val": "LEADID"
},
{
"content": "1325469000000075001",
"val": "SMOWNERID"
},
{
"content": "Geoff",
"val": "Lead Owner"
},
]
},
{
"no": "2",
"FL": [
{
"content": "1325469000000659017",
"val": "LEADID"
},
{
"content": "1325469000000075001",
"val": "SMOWNERID"
},
{
"content": "Geoff",
"val": "Lead Owner"
},
]
},
]
}
},
"uri": "/crm/private/json/Leads/getRecords"
}
}
I am using the following classes:
public class Row
{
[JsonProperty(PropertyName = "row")]
public List<Leads> row { get; set; }
}
public class Leads
{
[JsonProperty(PropertyName = "no")]
public string nbr { get; set; }
[JsonProperty(PropertyName = "FL")]
public List<Lead> FieldValues { get; set; }
}
public class Lead
{
[JsonProperty(PropertyName = "content")]
public string Content { get; set; }
[JsonProperty(PropertyName = "val")]
public string Val { get; set; }
}
I try to deserialize the json and get back nothing:
var mList = JsonConvert.DeserializeObject<IDictionary<string, Row>>(result);
This is the first time working with Json so any help would be appreciated!
Usually when that happens it is because your class model for deserialization is wrong. Rather than trying to hand-craft the classes I like to use http://json2csharp.com. Just plug in your JSON and it gives you the necessary C# classes. In your case it provides the following.
public class FL
{
public string content { get; set; }
public string val { get; set; }
}
public class Row
{
public string no { get; set; }
public List<FL> FL { get; set; }
}
public class Leads
{
public List<Row> row { get; set; }
}
public class Result
{
public Leads Leads { get; set; }
}
public class Response
{
public Result result { get; set; }
public string uri { get; set; }
}
public class RootObject
{
public Response response { get; set; }
}
You can then deserialize into RootObject using:
var mList = JsonConvert.DeserializeObject<RootObject>(result);
Feel free to rename RootObject to whatever name you like better.