Search code examples
c#shodan

Deserialize shodan data


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

Solution

  • 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.