Deserializing Jarray in JSON.NET - json

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);
}
}

Related

Deserializing JSON from URL - how do I add it to multiple objects

So basically I ran the JSON through jsonUtils which created an object, which turned out to be several objects.
So 2 questions please:
How to best populate objects from URL?
Can I select which objects to populate, i.e. I don't want to do all 20 objects?
In advance, thank you!!
WebClient client = new WebClient();
string myJSON = client.DownloadString("https://someURL.geojson");
var myClass = Newtonsoft.Json.JsonConvert.DeserializeObject(myJSON);
Console.Write(myClass.ToString());
public class PrecipType
{
public string units { get; set; }
public string value { get; set; }
}
public class Press
{
public string units { get; set; }
public string value { get; set; }
}
public class Atmo
{
public AirTemperature air_temp{ get; set; }
public Dewpoint dew_point{ get; set; }
public Wind { get; set; }
public Pressure pressure { get; set; }
}
public class ObsTime
{
public string units { get; set; }
public string value { get; set; }
}

Implementing deserialization with RestSharp and Newtonsoft.Json

I am rather new to c# but I am building something to help me at work. We have a REST API which I am trying to tap into but I am having issues when it comes to deserializing the response.
My code:
namespace BSRestCleint
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
string key = "xxxxxxxx";
string endPoint = "https://api.broadsign.com:10889/rest";
private void bRun_Click(object sender, EventArgs e)
{
var client = new RestClient(endPoint);
var request = new RestRequest("/host/v14/by_id", Method.GET);
request.AddHeader("accept", "application/json");
request.AddHeader("Authorization", "Bearer " + key);
request.AddParameter("domain_id", "103947039");
request.AddParameter("ids", "195392183");
request.OnBeforeDeserialization = resp => { resp.ContentType = "application/json"; };
request.RequestFormat = DataFormat.Json;
var response = client.Execute<Host>(request);
var host = JsonConvert.DeserializeObject<Host>(response.Content);
oResponse.Text = host.Name;
}
}
}
And this is my class:
namespace BSRestCleint
{
using System;
using System.Collections.Generic;
using System.Globalization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.Runtime.Serialization.Json;
using System.IO;
public partial class Host
{
[JsonProperty("config_profile_bag_id")]
public long ConfigProfileBagId { get; set; }
[JsonProperty("container_id")]
public long ContainerId { get; set; }
[JsonProperty("db_pickup_tm_utc")]
public string DbPickupTmUtc { get; set; }
[JsonProperty("discovery_status")]
public long DiscoveryStatus { get; set; }
[JsonProperty("display_unit_id")]
public long DisplayUnitId { get; set; }
[JsonProperty("domain_id")]
public long DomainId { get; set; }
[JsonProperty("geolocation")]
public string Geolocation { get; set; }
[JsonProperty("id")]
public long Id { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("nscreens")]
public long Nscreens { get; set; }
[JsonProperty("public_key_fingerprint")]
public string PublicKeyFingerprint { get; set; }
[JsonProperty("remote_clear_db_tm_utc")]
public string RemoteClearDbTmUtc { get; set; }
[JsonProperty("remote_reboot_tm_utc")]
public string RemoteRebootTmUtc { get; set; }
[JsonProperty("volume")]
public long Volume { get; set; }
}
}
Finally the returning json:
{
"not_modified_since":"2018-06-05T22:22:18Z",
"host":[
{
"active":true,
"config_profile_bag_id":0,
"container_id":0,
"db_pickup_tm_utc":"2018-01-11T10:12:55",
"discovery_status":0,
"display_unit_id":0,
"domain_id":103947039,
"geolocation":"(0,0)",
"id":195392183,
"license_end_date":null,
"licensed":true,
"name":"Broadsign Services - Mathias - 16x64",
"nscreens":0,
"primary_mac_address":"00:0c:29:e0:e6:22",
"public_key_fingerprint":"REDACTED",
"remote_clear_db_tm_utc":"1970-01-01T00:00:00",
"remote_reboot_tm_utc":"2017-12-12T10:17:23",
"secondary_mac_address":"",
"volume":-1
}
]
}
I know that if I only process this part my code works:
{
"active":true,
"config_profile_bag_id":0,
"container_id":0,
"db_pickup_tm_utc":"2018-01-11T10:12:55",
"discovery_status":0,
"display_unit_id":0,
"domain_id":103947039,
"geolocation":"(0,0)",
"id":195392183,
"license_end_date":null,
"licensed":true,
"name":"Broadsign Services - Mathias - 16x64",
"nscreens":0,
"primary_mac_address":"00:0c:29:e0:e6:22",
"public_key_fingerprint":"REDACTED",
"remote_clear_db_tm_utc":"1970-01-01T00:00:00",
"remote_reboot_tm_utc":"2017-12-12T10:17:23",
"secondary_mac_address":"",
"volume":-1
}
I'd like to know how I could make my code work to handle the whole json so that I don't need to regex the returning value. Some of the responses would return multiple instances unlike there where there's only 1. It's probably a very simple solution but my grasp of the language is rather minute as I am new to it.
Any help would be appreciated.
Since, you are getting the host as array inside the another root object so you can define a new class as which is wrapping Host (array)
public class RootObject
{
public DateTime not_modified_since { get; set; }
public List<Host> Host { get; set; }
}
deserialization code need to be updated as
var root = JsonConvert.DeserializeObject<RootObject>(response.Content);
If you see, here deserializtion will happen for RootObject instead of Host.
Now, to get all hosts, use the below code:
var hosts = root.Host;
Or the first host from received hosts
var firstHost = root.Host.First();
You can extract it like this, without introducing new class:
var js = JObject.Parse(response.Content);
var hosts = JArray.Parse(obj["host"].ToString());
foreach (JObject host in hosts)
{
var h = JsonConvert.DeserializeObject<Host>(host)
//do what you need to do with host
}
You mentioned that there can be multiple hosts, so, you have to convert it to JArray, and loop through the array.
use this as your Host class instead (renamed to RootObject)
public partial class RootObject
{
[JsonProperty("not_modified_since")]
public DateTimeOffset NotModifiedSince { get; set; }
[JsonProperty("host")]
public List<Host> Host { get; set; }
}
public partial class Host
{
[JsonProperty("active")]
public bool Active { get; set; }
[JsonProperty("config_profile_bag_id")]
public long ConfigProfileBagId { get; set; }
[JsonProperty("container_id")]
public long ContainerId { get; set; }
[JsonProperty("db_pickup_tm_utc")]
public DateTimeOffset DbPickupTmUtc { get; set; }
[JsonProperty("discovery_status")]
public long DiscoveryStatus { get; set; }
[JsonProperty("display_unit_id")]
public long DisplayUnitId { get; set; }
[JsonProperty("domain_id")]
public long DomainId { get; set; }
[JsonProperty("geolocation")]
public string Geolocation { get; set; }
[JsonProperty("id")]
public long Id { get; set; }
[JsonProperty("license_end_date")]
public object LicenseEndDate { get; set; }
[JsonProperty("licensed")]
public bool Licensed { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("nscreens")]
public long Nscreens { get; set; }
[JsonProperty("primary_mac_address")]
public string PrimaryMacAddress { get; set; }
[JsonProperty("public_key_fingerprint")]
public string PublicKeyFingerprint { get; set; }
[JsonProperty("remote_clear_db_tm_utc")]
public DateTimeOffset RemoteClearDbTmUtc { get; set; }
[JsonProperty("remote_reboot_tm_utc")]
public DateTimeOffset RemoteRebootTmUtc { get; set; }
[JsonProperty("secondary_mac_address")]
public string SecondaryMacAddress { get; set; }
[JsonProperty("volume")]
public long Volume { get; set; }
}
}
then deserialize
var rootObject = JsonConvert.DeserializeObject<RootObject>(response.Content);
var hosts = rootObject .Host;

Extracting JSON data using Newtonsoft in xamarin.android

Hello I am getting JSON data from server and i want to extract that JSON in Xamarin. How can i parse that JSON using NewTonSoft
below is the JSON responce i receive
[
{
"Id": 5,
"AlbumKey": "2REC2ZDSFK",
"ZipFillPath": "aaaa#gmail.com\\2REC2ZDSFK",
"NoOfPages": 3,
"EmailID": "aaaa#gmail.com"
}
]
This should be your Model
public class RootObject
{
public int Id { get; set; }
public string AlbumKey { get; set; }
public string ZipFillPath { get; set; }
public int NoOfPages { get; set; }
public string EmailID { get; set; }
}
Then
RootObject myObj = JsonConvert.DeserializeObject<RootObject>(json);
If your json is a List of objects, something like
List<RootObject> myListObj = JsonConvert.DeserializeObject<List<RootObject>>(json);
public class yourClass
{
public int Id { get; set; }
public string AlbumKey { get; set; }
public string ZipFillPath { get; set; }
public int NoOfPages { get; set; }
public string EmailID { get; set; }
}
Considering this as your model class you can
var responseText= JsonConvert.DeserializeObject<yourClass>(jsonResponse);
Then depending on if its a list or a not you can get the data from it
In case you are unable to find the class what you can do is check if the namespace of your current class and that class is the same.

{"No parameterless constructor defined for type of 'System.String[]'."} while deserailsing json data

This is my controller
[NoCache]
public ActionResult SaveAssociate(string data)
{
JavaScriptSerializer json = new JavaScriptSerializer();
List<string> mystring = json.Deserialize<List<string>>(data);
return Content("Hai");
}
Expression data
value :
[{"AssetName":"8888","AssetNumber":"8888","Classification":null,"ParentAsset":null,"SerialNumber":"8888","ParentCompany":"JPL Holdings","Barcode":null,"RFIDTags":null,"AssetId":"dfe2ae51-f153-4a67-bd3b-0114d8a40751","Notes":null,"Manufacturer":null,"DepartmentId":null,"Department":null,"SupplierId":null,"Supplier":null},{"AssetName":"552014","AssetNumber":"552014","Classification":null,"ParentAsset":"8888","SerialNumber":"552014","ParentCompany":"JPL Holdings","Barcode":null,"RFIDTags":null,"AssetId":"4109ba40-af78-486a-a40e-1d14a2d7b42f","Notes":null,"Manufacturer":null,"DepartmentId":null,"Department":null,"SupplierId":null,"Supplier":null},{"AssetName":"201","AssetNumber":"201","Classification":null,"ParentAsset":null,"SerialNumber":"2011","ParentCompany":"JPL Holdings","Barcode":null,"RFIDTags":null,"AssetId":"3e552280-16df-4c17-a4a5-1f61c4c96835","Notes":null,"Manufacturer":null,"DepartmentId":null,"Department":null,"SupplierId":null,"Supplier":null}]
At this line List<string> mystring = json.Deserialize<List<string>>(data);
am getting
{"No parameterless constructor defined for type of 'System.String[]'."}
even i tried like this
[Serializable]
public class GetUser
{
public GetUserdata[] Data { get; set; }
}
[Serializable]
public class GetUserdata
{
public string AssetName { get; set; }
public string AssetNumber { get; set; }
public string Classification { get; set; }
public string ParentAsset { get; set; }
public string SerialNumber { get; set; }
public string ParentCompany { get; set; }
public string Barcode { get; set; }
public string RFIDTags { get; set; }
public string AssetId { get; set; }
public string Notes { get; set; }
public string Manufacturer { get; set; }
public string DepartmentId { get; set; }
public string Department { get; set; }
public string SupplierId { get; set; }
public string Supplier { get; set; }
}
controller
public ActionResult SaveAssociate(string data)
{
JavaScriptSerializer json = new JavaScriptSerializer();
GetUser mystring = json.Deserialize<GetUser>(data);
return Content("Hai");
}
Am getting error
Type 'AssetTrackingSystem.Model.GetUser' is not supported for deserialization of an array.
Help me
Instead of the above code, could you try:
public ActionResult SaveAssociate(string data)
{
JavaScriptSerializer json = new JavaScriptSerializer();
GetUserdata[] myUsers = json.Deserialize<GetUserdata[]>(data);
return Content("Hai");
}
Because your Json is sent as an array of object not an object of array.
I hope it will help you.

How can I deserialization JSON in Windows Phone?

The first JSON is look like this
The second JSON is look like this
How can I deserialize them? I have been follow this example but it's not working.
Here's my code.
protected override void OnNavigatedTo(NavigationEventArgs e)
{
var w = new WebClient();
Observable
.FromEvent<DownloadStringCompletedEventArgs>(w, "DownloadStringCompleted")
.Subscribe(r =>
{
var deserialized =
JsonConvert.DeserializeObject<List<Place>>(r.EventArgs.Result);
PlaceList.ItemsSource = deserialized;
});
w.DownloadStringAsync(
new Uri("http://mobiilivantaa.lightscreenmedia.com/api/place"));
//For 2nd JSON
//w.DownloadStringAsync(
//new Uri("http://mobiilivantaa.lightscreenmedia.com/api/place/243"));
}
These are classes for 1st JSON.
public class Place
{
public string id { get; set; }
public string title { get; set; }
public string latitude { get; set; }
public string longitude { get; set; }
public string www { get; set; }
}
public class RootObjectJSON1
{
public List<Place> Places { get; set; }
}
These are classes for JSON2
public class Address
{
public string street { get; set; }
public string postal_code { get; set; }
public string post_office { get; set; }
}
public class Image
{
public string id { get; set; }
public string filename { get; set; }
public string path { get; set; }
}
public class RootObjectJSON2
{
public string id { get; set; }
public string title { get; set; }
public string description { get; set; }
public string latitude { get; set; }
public string longitude { get; set; }
public string www { get; set; }
public string phone { get; set; }
public string email { get; set; }
public string contact_person { get; set; }
public Address address { get; set; }
public List<Image> images { get; set; }
}
it looks that you should be deserializing object RootObjectJSON1 or RootObjectJSON2, e.g.:
var deserialized = JsonConvert.DeserializeObject<RootObjectJSON1>(r.EventArgs.Result);
Also it seems that collection Places should be with lowercase p at beginning or you need to tell Json.NET that this property should be deserialized with different name, e.g.:
[JsonProperty(PropertyName="places")]
public List<Place> Places { get; set; }
Generally I tend to use arrays for deserialization (from my experience works better) so I'll suggest to rewrite it to this:
public class RootObjectJSON1
{
public Place[] places { get; set; }
}
There is very good tool named json2csharp available at http://json2csharp.com/ - just put sample of JSON there and it will spit out classes in C# (doesn't detect DateTime so you might need to change that).