Deserialize shodan data - c#

I'm having problems deserializing the data I'm getting from Shodan. Below are the classes I got from json2csharp and I'm trying to create an array of the matches and loop through them. It seems like I have tried with everything except a working array by now. The data itself is matches as root with objects of them that contain location (with its own data etc). An except below that I cut out a bit.
This is my error:
Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'Shodan.Match[]' because the type requ
ires a JSON array (e.g. [1,2,3]) to deserialize correctly.
var data = JsonConvert.DeserializeObject<Match[]>(allData);
{"matches": [{"product": "product", "hash": 0, "ip": 123123, "isp": "Verizon Internet Services"}], "total": 1}
public class Location
{
public string city { get; set; }
public string region_code { get; set; }
public object area_code { get; set; }
public double longitude { get; set; }
public string country_code3 { get; set; }
public double latitude { get; set; }
public string postal_code { get; set; }
public object dma_code { get; set; }
public string country_code { get; set; }
public string country_name { get; set; }
}
public class Options
{
}
public class Shodan
{
public string crawler { get; set; }
public string id { get; set; }
public string module { get; set; }
public Options options { get; set; }
}
public class Match
{
public int hash { get; set; }
public int ip { get; set; }
public string isp { get; set; }
public string transport { get; set; }
public string data { get; set; }
public string asn { get; set; }
public int port { get; set; }
public List<string> hostnames { get; set; }
public Location location { get; set; }
public DateTime timestamp { get; set; }
public List<string> domains { get; set; }
public string org { get; set; }
public object os { get; set; }
public Shodan _shodan { get; set; }
public string ip_str { get; set; }
public string product { get; set; }
}
public class RootObject
{
public List<Match> matches { get; set; }
public int total { get; set; }
}

You could create another class like
var allData =
{"matches": [{"product": "product", "hash": 0, "ip": 123123, "isp": "Verizon Internet Services"}], "total": 1}
public class MyMatches {
public Match[] matches {get; set;}
}
and then use that in the deserializer.
var data = JsonConvert.DeserializeObject<MyMatches>(allData);
This is if the JSON code sample you gave us is correct.
CORRECTION
Just saw the RootObject class.
Just use that.

Related

JSON DeserializeObject to Model without Key Name

I currently have JSON coming in as follows:
{"36879":[{"min_qty":1,"discount_type":"%","csp_price":10}],"57950":[{"min_qty":1,"discount_type":"flat","csp_price":650}]}
This contains a list of the following records
ProductId
MinQty
DiscountType
Price
I need to deserialize this into the following model:
public class CustomerSpecificPricing
{
string productId { get; set; }
public virtual List<CustomerSpecificPricingDetail> CustomerSpecificPricingDetails { get; set; }
}
public class CustomerSpecificPricingDetail
{
public string min_qty { get; set; }
public string discount_type { get; set; }
public string csp_price { get; set; }
}
The problem is that the "productId" of each record is missing the key name.
If I run my JSON through J2C, I get the following:
public class 36879 {
public int min_qty { get; set; }
public string discount_type { get; set; }
public int csp_price { get; set; }
}
public class 57950 {
public int min_qty { get; set; }
public string discount_type { get; set; }
public int csp_price { get; set; }
}
public class Root {
public List<_36879> _36879 { get; set; }
public List<_57950> _57950 { get; set; }
}
Which is obviously incorrect.
How would I deserialize my object correctly?
You would need to deserialize it into a dictionary first and then map it into the format you require after. Something like this should work:
var dict = JsonConvert.DeserializeObject<Dictionary<string, IEnumerable<CustomerSpecificPricingDetail>>>();
var result = dict.Select(kvp => new CustomerSpecificPricing { ProductId = Int32.Parse(kvp.Key), CustomerSpecificPricingDetails = kvp.Value });
Id also recommend you follow the conventional standards of naming. In this case properties in classes should be PascalCase,
e.g. your classes now become:
public class CustomerSpecificPricing
{
[JsonProperty("productId ")]
public string ProductId { get; set; }
public virtual List<CustomerSpecificPricingDetail> CustomerSpecificPricingDetails { get; set; }
}
and
public class CustomerSpecificPricingDetail
{
[JsonProperty("min_qty")]
public string MinQty { get; set; }
[JsonProperty("discount_type ")]
public string DiscountType { get; set; }
[JsonProperty("csp_price ")]
public string CspPrice { get; set; }
}

C# Getting individual data from JSON text downloaded from a site

I've been searching around for a long while for this, I haven't found any solutions to my issue which is:
I've been trying get a json data individually from a whole source seen here:
{"TargetId":0,"ProductType":null,"AssetId":1239281845,"ProductId":0,"Name":"❤️🍀𝐒𝐀𝐋𝐄❗️🍀❤️ Red&Black Flannel + Backpack","Description":"Shirt Image","AssetTypeId":1,"Creator":{"Id":124026176,"Name":"TheDestroyerPeter","CreatorType":"User","CreatorTargetId":124026176},"IconImageAssetId":0,"Created":"2017-12-12T19:48:24.693Z","Updated":"2017-12-12T19:48:24.693Z","PriceInRobux":null,"PriceInTickets":null,"Sales":0,"IsNew":false,"IsForSale":false,"IsPublicDomain":false,"IsLimited":false,"IsLimitedUnique":false,"Remaining":null,"MinimumMembershipLevel":0,"ContentRatingTypeId":0}
now what I've been trying to do with it is get the Product Name using C# and the product name is "❤️🍀𝐒𝐀𝐋𝐄❗️🍀❤️ Red&Black Flannel + Backpack", my issue is that I haven't found a way to extract the data, and when I have I haven't been able to get the right data, because instead if gives me "TheDestroyerPeter"
I've written up code, and deleted it, it was really sloppy and it would take awhile to rewrite, I appreciate any solutions
-whoever I am
You can use JavaScriptSerializer class, which is part of the System.Web.Script namespace.
For example :
var jsonString = #"{""name"":""John Doe"",""age"":20}";
var JSONObj = new JavaScriptSerializer().Deserialize<Dictionary<string, string>>(jsonString );
and then JSONObj["name"]; gives you "John Doe"
in this case you can use it :
public class Creator
{
public int Id { get; set; }
public string Name { get; set; }
public string CreatorType { get; set; }
public int CreatorTargetId { get; set; }
}
public class RootObject
{
public int TargetId { get; set; }
public object ProductType { get; set; }
public int AssetId { get; set; }
public int ProductId { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public int AssetTypeId { get; set; }
public Creator Creator { get; set; }
public int IconImageAssetId { get; set; }
public DateTime Created { get; set; }
public DateTime Updated { get; set; }
public object PriceInRobux { get; set; }
public object PriceInTickets { get; set; }
public int Sales { get; set; }
public bool IsNew { get; set; }
public bool IsForSale { get; set; }
public bool IsPublicDomain { get; set; }
public bool IsLimited { get; set; }
public bool IsLimitedUnique { get; set; }
public object Remaining { get; set; }
public int MinimumMembershipLevel { get; set; }
public int ContentRatingTypeId { get; set; }
}
use Newtonsoft.Json
var jsonString = #"{""TargetId"":0,""ProductType"":null,""AssetId"":1239281845,""ProductId"":0,""Name"":""❤️🍀𝐒𝐀𝐋𝐄❗️🍀❤️ Red&Black Flannel + Backpack"",""Description"":""Shirt Image"",""AssetTypeId"":1,""Creator"":{""Id"":124026176,""Name"":""TheDestroyerPeter"",""CreatorType"":""User"",""CreatorTargetId"":124026176},""IconImageAssetId"":0,""Created"":""2017-12-12T19:48:24.693Z"",""Updated"":""2017-12-12T19:48:24.693Z"",""PriceInRobux"":null,""PriceInTickets"":null,""Sales"":0,""IsNew"":false,""IsForSale"":false,""IsPublicDomain"":false,""IsLimited"":false,""IsLimitedUnique"":false,""Remaining"":null,""MinimumMembershipLevel"":0,""ContentRatingTypeId"":0}";
var obj = JsonConvert.DeserializeObject<RootObject>(jsonString);
Console.WriteLine(obj.Creator.Name); //"TheDestroyerPeter"

Deserialized JSON String to C# Object gives the error "Cannot access static class in non-static context" when the object's methods are called

I'm trying to GET a JSON REST-api request, deserialize it using the Newtonsoft.Json package for .NET and access methods within the newly created object, but I keep getting an error that won't let me run my C# code in Visual Studio 2015.
For the following JSON string,
{
"pagination":
{
"per_page": 1,
"items": 28,
"page": 1,
"urls":
{
"last": "https://...",
"next": "https://..."
},
"pages": 28
},
"results":
[{
"style": ["House"],
"thumb": "https://...",
"format": ["File", "AAC", "Album"],
"country": "Unknown",
"barcode": ["id886037928"],
"uri": "/Porter-Robinson-Worlds/master/721049",
"community": {"have": 932, "want": 720},
"label": ["Astralwerks", "Sample Sized, LLC", "Astralwerks"],
"catno": "none",
"year": "2014",
"genre": ["Electronic"],
"title": "Porter Robinson - Worlds",
"resource_url": "https://...",
"type": "master",
"id": 721049
}]
}
I created the following C# object class:
public class Discogs
{
public class pagination
{
public int per_page { get; set; }
public int items { get; set; }
public int page { get; set; }
public class urls
{
public string last { get; set; }
public string next { get; set; }
}
public int pages { get; set; }
public class data
{
public string[] style { get; set; }
public string thumb { get; set; }
public string[] format { get; set; }
public string country { get; set; }
public string[] barcode { get; set; }
public string uri { get; set; }
public class community
{
public string have { get; set; }
public string want { get; set; }
}
public string[] label { get; set; }
public string catno { get; set; }
public string year { get; set; }
public string[] genre { get; set; }
public string title { get; set; }
public string resource_url { get; set; }
public string type { get; set; }
public string id { get; set; }
}
public class results
{
public data Results { get; set; }
}
}
}
In a private async void class, I've successfully fetched the GET request and stored it in the string, jsonstring. Now I try to run this code:
Discogs myUser = new Discogs();
myUser = JsonConvert.DeserializeObject<Discogs>(jsonstring);
int yr = myUser.pagination.data.year;
...but my project gets an error, An object reference is required for the non-static field, method, or property 'Discogs.pagination.data.year', cannot access non-static property 'year' in static context.
This does not make sense to me because I have no static classes or methods. I've searched for a solution but all similar problems seem to be able to access deserialized objects without any such error. Any help on accessing the methods in my Discogs object would be greatly appreciated.
The problem is that you are trying to use the class Pagination without instantiating the class. In order to use a non-static class (Pagination, Data, Community) you must first instantiate them like below
Pagination pag = new Pagination();
Your structure here is pretty odd. Normally classes would be in separate files or at least not nested such as you have here. You may want to rethink the way you've designed this program.
You are trying to get value from "myUser.pagination...", but in your example "pagination" is a class name not a property inside "Discogs" class, same as "data" inside "pagination" class
code with nested classes:
public class Discogs
{
public class Pagination
{
public int per_page { get; set; }
public int items { get; set; }
public int page { get; set; }
public class Urls
{
public string last { get; set; }
public string next { get; set; }
}
public Urls urls {get;set;}
public int pages { get; set; }
public class Data
{
public string[] style { get; set; }
public string thumb { get; set; }
public string[] format { get; set; }
public string country { get; set; }
public string[] barcode { get; set; }
public string uri { get; set; }
public class Community
{
public string have { get; set; }
public string want { get; set; }
}
public Community community { get; set; }
public string[] label { get; set; }
public string catno { get; set; }
public string year { get; set; }
public string[] genre { get; set; }
public string title { get; set; }
public string resource_url { get; set; }
public string type { get; set; }
public string id { get; set; }
}
public class Results
{
public Data Results { get; set; }
}
public Results result {get;set;}
}
public Pagination pagination {get;set}
}
code with i think a bit easy to understand:
public class Urls
{
public string last { get; set; }
public string next { get; set; }
}
public class Community
{
public string have { get; set; }
public string want { get; set; }
}
public class Data
{
public string[] style { get; set; }
public string thumb { get; set; }
public string[] format { get; set; }
public string country { get; set; }
public string[] barcode { get; set; }
public string uri { get; set; }
public string[] label { get; set; }
public string catno { get; set; }
public string year { get; set; }
public string[] genre { get; set; }
public string title { get; set; }
public string resource_url { get; set; }
public string type { get; set; }
public string id { get; set; }
public Community community { get; set; }
}
public class Results
{
public Data Results { get; set; }
}
public class Pagination
{
public int per_page { get; set; }
public int items { get; set; }
public int page { get; set; }
public int pages { get; set; }
public Urls urls {get;set;}
public Results result {get;set;}
}
public class Discogs
{
public Pagination pagination {get;set}
}

How should I handle Wordpress rest json in C# when json2csharp is returning an invalid name? [duplicate]

I have a JSON request which has follwing structure:
"formats": {
"flash_embed": "http://a3.vikiassets.com/assets/vikiplayer-922746a667cfd38137a7e45df6ba1b95.swf?auto_play=true&language_codes=en&media_id=74965&partner=16&source=api_v3",
"m3u8": "http://wpc.354a.edgecastcdn.net/00354A/videos/encoded/74965/ios.m3u8",
"res-150p": "http://wpc.354a.edgecastcdn.net/00354A/videos/encoded/74965_mp4cell_150.mp4",
"res-240p": "http://wpc.354a.edgecastcdn.net/00354A/videos/encoded/74965_240p.mp4",
"res-270p": "http://wpc.354a.edgecastcdn.net/00354A/videos/encoded/74965_270p.mp4",
"res-360p": "http://wpc.354a.edgecastcdn.net/00354A/videos/encoded/74965_360p.mp4",
"res-480p": "http://wpc.354a.edgecastcdn.net/00354A/videos/encoded/74965_480p.mp4",
"res-720p": "http://wpc.354a.edgecastcdn.net/00354A/videos/encoded/74965_720p.mp4"
}
}
Now res-150p, says invalid name in C# and if I give another name to it then while desiralizing I am not getting any values, that is null inside res-150p.
Edit:
[Serializable]
MoviesListRootObject is the root Object which Contains Response and then Response Contains Formats
public class MoviesListRootObject
{
public int count { get; set; }
public Pagination pagination { get; set; }
public List<Response> response { get; set; }
}
[Serializable]
public class Response
{
public int id { get; set; }
public int channel_id { get; set; }
public string title { get; set; }
public string title_language { get; set; }
public string description { get; set; }
public string description_language { get; set; }
public string created_at { get; set; }
public string uri { get; set; }
public string web_uri { get; set; }
public List<object> genres { get; set; }
public string origin_country { get; set; }
public string image { get; set; }
public Subtitles subtitles { get; set; }
public Formats formats { get; set; }
}
[Serializable]
public class Formats
{
public string flash_embed { get; set; }
public string m3u8 { get; set; }
public string __invalid_name__res150p { get; set; }
public string __invalid_name__res240p { get; set; }
public string __invalid_name__res270p { get; set; }
public string __invalid_name__res360p { get; set; }
public string __invalid_name__res480p { get; set; }
public string __invalid_name__res720p { get; set; }
public string __invalid_name__flv480p { get; set; }
public string __invalid_name__flv360p { get; set; }
public string __invalid_name__flv270p { get; set; }
public string __invalid_name__flvvp6360p { get; set; }
public string __invalid_name__flvvp6270p { get; set; }
}
You have to decorate your Formats properties with JsonProperty attributes to tell it what goes where if the name does not exactly match:
partial class Formats
{
[JsonProperty("res-150p")]
public string __invalid_name__res150p {get; set;}
}
See also Using JsonConvert.DeserializeObject to deserialize Json to a C# POCO class

Deserializing this JSON response to C#

I have this specific JSON response that I am trying to deserialize without success. I am hoping someone can help me.
Here is the JSON response I get:
{
"num_locations": 1,
"locations": {
"98765": {
"street1": "123 Fake Street",
"street2": "",
"city": "Lawrence",
"state": "Kansas",
"postal_code": "66044",
"s_status": "20",
"system_state": "Off"
}
}
}
I used json2csharp http://json2csharp.com and got these recommended classes:
public class __invalid_type__98765
{
public string street1 { get; set; }
public string street2 { get; set; }
public string city { get; set; }
public string state { get; set; }
public string postal_code { get; set; }
public string s_status { get; set; }
public string system_state { get; set; }
}
public class Locations
{
public __invalid_type__98765 __invalid_name__98765 { get; set; }
}
public class RootObject
{
public int num_locations { get; set; }
public Locations locations { get; set; }
}
But when I try to use it in my code:
var locationResponse = JsonConvert.DeserializeObject<RootObject>(response.Content);
What I get is (Watch):
locationResponse : {RestSharpConsoleApplication.Program.RootObject} : RestSharpConsoleApplication.Program.RootObject
locations : {RestSharpConsoleApplication.Program.Locations} : RestSharpConsoleApplication.Program.Locations
__invalid_name__98765 : null : RestSharpConsoleApplication.Program.__invalid_type__98765
num_locations : 1 : int
Obviously I am not creating (json2csharp) the right classes for the DeserializeObject, and sadly I have no control over the JSON response (vendor = SimpliSafe).
It is obvious the "98765" is meant to be a value (location number) but json2csharp makes it into this __invalid_type__98765 class and this is probably why it gets null.
Any idea how should the classes look for this particular JSON to be successfully deserialized?
Thanks!
Zachs
You should be able to do this with a dictionary:
public class MyData{
[JsonProperty("locations")]
public Dictionary<string, Location> Locations {get;set;}
}
public class Location
{
public string street1 { get; set; }
public string street2 { get; set; }
public string city { get; set; }
public string state { get; set; }
public string postal_code { get; set; }
public string s_status { get; set; }
public string system_state { get; set; }
}
Do you have a non-Express version of Visual Studio? If so, copy the JSON to clipboard and then go to the Visual Studio menu: Edit >> Paste special >> Paste JSON as classes.
Using that gives:
public class Rootobject {
public int num_locations { get; set; }
public Locations locations { get; set; }
}
public class Locations {
public _98765 _98765 { get; set; }
}
public class _98765 {
public string street1 { get; set; }
public string street2 { get; set; }
public string city { get; set; }
public string state { get; set; }
public string postal_code { get; set; }
public string s_status { get; set; }
public string system_state { get; set; }
}
That suggests your JSON structure is not quite right.
You can also specify the property name via an attribute to use to get around this:
public class RootObject
{
public int num_locations { get; set; }
public Locations locations { get; set; }
}
public class Locations
{
[JsonProperty("98765")]
public LocationInner Inner { get; set; }
}
public class LocationInner
{
public string street1 { get; set; }
public string street2 { get; set; }
public string city { get; set; }
public string state { get; set; }
public string postal_code { get; set; }
public string s_status { get; set; }
public string system_state { get; set; }
}
...but it would really be better if the JSON were properly formatted such that the Locations was actually an array of location objects.

Categories