deserialize POCO array with JsonFX - c#

I want to simply read some JSON data from a URL, then turn that into an collection of POCO classes, but I can't seem to figure out what I'm doing wrong.
Here is a sample of the JSON data, as it is fetched from the URL:
[
{
"Name":"Together As One Run",
"Location":"Parkville, MO",
"ScheduledAt":"\/Date(1334984400000)\/",
"URL":"http://www.runningintheusa.com/Race/View.aspx?RaceID=36667"
},
{
"Name":"Lean Green Running Machine 5K Run/Walk and 1 Mile Run",
"Location":"Springfield, MO",
"ScheduledAt":"\/Date(1335589200000)\/",
"URL":"http://www.runningintheusa.com/Race/View.aspx?RaceID=53945"
},
{
"Name":"Festival of Miles",
"Location":"St. Louis, MO",
"ScheduledAt":"\/Date(1338440400000)\/",
"URL":"http://www.runningintheusa.com/Race/View.aspx?RaceID=53901"
},
{
"Name":"Miles Against Melanoma",
"Location":"Saint Charles, MO",
"ScheduledAt":"\/Date(1338613200000)\/",
"URL":"http://www.runningintheusa.com/Race/View.aspx?RaceID=53939"
}
]
I can get this data with WebClient just fine.
I'm setting up my JsonFX reader like this:
var json = new JsonReader(new DataReaderSettings(new PocoResolverStrategy()));
Here is my POCO class:
public class Race {
public String Name { get; set; }
public String Location { get; set; }
public DateTime ScheduledAt { get; set; }
public String URL { get; set; }
}
I have tried to deserialize JSON data in several ways, and nothing seems to work:
//reader is an instance of StreamReader
var content = reader.ReadToEnd();
//nope
//var output = json.Read<Race>(content);
//nope
//var output = json.Read<Race[]>(content);
This has got to be a simple thing to do, I just can't find a solution. I spent about 30 mins. googling to no avail. Any help would be appreciated!

I've never used JsonFX but you can try Json.Net or built-in JavaScriptSerializer. Both work without any problem.
var jObj1 = JsonConvert.DeserializeObject<Race[]>(jsonstr);
var jobj2 = new JavaScriptSerializer().Deserialize<Race[]>(jsonstr);

edit oops, didn't read the title. Why are you using jsonfx?
maybe try a list?
var output = json.Read<List<Race>>(input);
Here is a valid example of how to get it done with JSON.Net.
You're going to want to use JSON.NET. It's faster than any of the built in classes and does a much better job of serializing dictionaries.
using Nuget
> Install-Package Newtonsoft.Json
List<Race> deserializedRaces = JsonConvert.DeserializeObject<List<Race>>(jsonString);

I bet you need to specify the datacontract and datamember attributes on your custom type for jsonFX to recognize it.
using System.Runtime.Serialization;
[DataContract]
public class Race {
[DataMember]
public String Name { get; set; }
[DataMember]
public String Location { get; set; }
[DataMember]
public DateTime ScheduledAt { get; set; }
[DataMember]
public String URL { get; set; }
}

You probably need to tell it to try parsing your date as a Microsoft-style date time:
var jsonReader = new JsonReader(
new DataReaderSettings(
new PocoResolverStrategy(),
new MSAjaxDateFilter()));

Related

How do I parse JSON data which contains only arrays and nested arrays with no property names?

So I've looked around for tutorials on this and all the tutorials I've found doesn't have JSON that looks like the one I'm trying to parse.
I'm trying to parse JSON from this website https://www.steamcardexchange.net/api/request.php?GetBadgePrices_Guest
Since it doesn't have any identifiers for each thing like name, id etc I'm not sure how I will go about extracting data from it.
My only interest is really getting the first number of each item
[["449940","! That Bastard Is Trying To Steal Our Gold !"],5,"$0.64","1519294200"]
so what I want to extract from this item would be "449940".
This is what I've got so far
using (var client = new WebClient())
{
client.DownloadFile("https://www.steamcardexchange.net/api/request.php?GetBadgePrices_Guest", "data.json");
}
using (StreamReader r = new StreamReader("data.json"))
{
string json = r.ReadToEnd();
//Parse somehow
}
Any tips?
I took this up out of sheer curiosity because I had no idea how to parse this either. Perhaps there's a much better way.
I started by pasting a fragment of this into json2csharp.com.
The class it generates is
public class RootObject
{
public List<List<object>> data { get; set; }
}
From there I wrote some classes that correspond to what I think the data is supposed to look like. The names of the classes and properties are meaningless, so change them to whatever these actually represent.
public class OutputItem
{
public Message Message { get; set; }
public long Int64Value { get; set; } // 5
public string StringThatLooksLikeCurrency { get; set; } // "$0.64"
public string StringThatLooksNumeric { get; set; } // "1519294200"
}
public class Message
{
public string MessageId { get; set; } // "449940"
public string MessageText { get; set; } // "! That Dude..."
}
And finally, some sample code that takes a fragment of that JSON and converts it to a list of OutputItem. In order to figure this out I first deserialized the JSON to RootObject, then I inspected the deserialized object in the debugger to make sense of what it looked like.
var json = #"{ ""data"": [[[ ""449940"", ""! That Dude Is Trying To Steal Our Gold !"" ], 5, ""$0.64"", ""1519294200"" ], [[ ""303720"", ""#killallzombies"" ], 5, ""$0.56"", ""1519322799"" ]]}";
var parsed = JsonConvert.DeserializeObject<RootObject>(json);
var outputItems = new List<OutputItem>();
foreach (var listOfObject in parsed.data)
{
var outputItem = new OutputItem();
var message = (JArray) listOfObject[0];
outputItem.Message = new Message {MessageId = (string) message[0],
MessageText = (string) message[1]};
outputItem.Int64Value = (long) listOfObject[1];
outputItem.StringThatLooksLikeCurrency = (string) listOfObject[2];
outputItem.StringThatLooksNumeric = (string) listOfObject[3];
outputItems.Add(outputItem);
}

How to get json data using c#?

string json string = {\"GetMyClassListResult\":{\"MyClassList\":[{\"Id\":1,\"Amount\":\"5,00\"},{\"Id\":2,\"Amount\":\"10,00\"},{\"Id\":3,\"Amount\":\"20,00\"},{\"Id\":4,\"Amount\":\"25,00\"}],\"ReturnValues\":{\"ErrorCode\":1,\"ErrorDescription\":\"Successful\"}}}
How do get "Id":1" and "Amount":"5,00" ?
First, you would need to declare a class as following.
class MyClass
{
[JsonProperty(PropertyName = "Id")]
public int Id { get; set; }
[JsonProperty(PropertyName = "Amount")]
public string Amount { get; set; }
}
and then, you can do the following in your method
var Jsonobj = JObject.Parse(json);
var list = JsonConvert.DeserializeObject<MyClass[]>(Jsonobj["GetMyClassListResult"]["MyClassList"].ToString()).ToList<MyClass>();
Hope that helps.
Combining the excellent Json.NET package with LINQ you could use:
var result = JObject.Parse(json)["GetMyClassListResult"]["MyClassList"]
.Select(item => new { Id = item["Id"], Amount = item["Amount"] })
.First();
result has the properties Id and Amount corresponding to the first item in the JSON array with values 1 and "5,00".
If instead you wanted an array of all items, just replace First() with ToArray().
So you have straight json and you're trying to convert it into an object to get some meaningful values?
I personally prefer working with classes where I can. I will throw my raw json into a json to C# converter. I like JsonUtils personally. (I have no affiliation, just a great free service.) There are some others out there, but it seems to be the most robust.
If you throw your raw json into there, you get the following classes:
public class MyClassList
{
public int Id { get; set; }
public string Amount { get; set; }
}
public class ReturnValues
{
public int ErrorCode { get; set; }
public string ErrorDescription { get; set; }
}
public class GetMyClassListResult
{
public IList<MyClassList> MyClassList { get; set; }
public ReturnValues ReturnValues { get; set; }
}
public class Example
{
public GetMyClassListResult GetMyClassListResult { get; set; }
}
Alright. Now that we have our models, we can deserialize the json. The most popular library for manipulating json is Newtonsoft.Json, which is available on NuGet or direct download.
You'll need to add a reference to that dll if you choose to download it; Nuget will auto-reference it when you install it.
At the top of your class file, you'll need to add
using Newtonsoft.Json;
along with your other using statements.
In your method you'll call JsonConvert.Deserialize<List<Example>>(json), which will give you your collection in POCOs.
Since there is only one object in the collection you can call .First() on the collection and then access the two values via the Id and Amount properties. You will need to make sure that System.Linq is in your using statements as well.
Full code:
var json = #"{\"GetMyClassListResult\":{\"MyClassList\":[{\"Id\":1,\"Amount\":\"5,00\"},{\"Id\":2,\"Amount\":\"10,00\"},{\"Id\":3,\"Amount\":\"20,00\"},{\"Id\":4,\"Amount\":\"25,00\"}],\"ReturnValues\":{\"ErrorCode\":1,\"ErrorDescription\":\"Successful\"}}}";
var collection = JsonConvert.Deserialize<List<Example>>(json);
var x = collection.First();
var amount = x.Amount;
var id = x.Amount;
You're then free to manipulate or work with those variables as you see fit. :)
first of all you need a class where you will de-serialize this string to your class object.
you need a class which will contain Id and Amount variable.
after that you can de-serialize this string to the object then you can access any data you want.

Parsing complex JSON text with Json.NET

I am writing a program to access Mediafire's web API and it's all going well, the only issue remaining is the response text in JSON format that I have difficulty parsing.
With API calls like creating a folder, I get a simple response which can be deserialized into a Dictionary<string,Dictionary<string,string>> and searched for values:
{"response":
{
"action":"folder\/create.php",
"name":"blargh",
"folder_key":"mmttuu769djo0",
"result":"Success",
"current_api_version":"2.14"
}
}
I would use it like this:
Dictionary<string,string> json = DeserializeJSON(text)["response"];
//DeserializeJSON is a method to shorten:
//JsonConvert.DeserializeObject<Dictionary<string,Dictionary<string,string>>(text)
I can then query for json["result"] and whatnot. With other API calls I get complex structures that I'm not sure how to handle. It's basically a bunch of key:value pairs, but some of the values are key:value pairs as well, which can't be put into a dictionary like I'm currently doing. I'm fairly new to C# so I'm not sure what to do here, is there some other data type like a Dictionary which doesn't have static types?
Here's the response:
{"response":
{
"action":"upload\/upload.php",
"doupload":
{
"result":"0",
"key":"89lh7760x4l"
},
"server":"live",
"result":"Success",
"current_api_version":"2.14"
}
}
My question would be: What is a good way to get this kind of data into a list that I can query for values?
What about creating a new class(s) to deal with the json? You can generate classes by using json2csharp using the example json.
public class Doupload
{
public string result { get; set; }
public string key { get; set; }
}
public class Response
{
public string action { get; set; }
public Doupload doupload { get; set; }
public string server { get; set; }
public string result { get; set; }
public string current_api_version { get; set; }
}
public class RootObject
{
public Response response { get; set; }
}
Then you can deserialise the json using:
JavaScriptSerializer serializer = new JavaScriptSerializer();
var something = serializer.Deserialize<RootObject>(jsonString);
I ended up finding out about the dynamic type - Deserializing the text into a Dictionary<string,dynamic> allows it to have multiple types where some can be dictionaries as well. I can query it as I would expect but I just need to be sure what values are returned with each API call, and I need to cast it to a string.
string upload_key = (string)json["response"]["doupload"]["key"] //89lh7760x4l

DataContractJsonSerializer returning null object

I've been struggling with this problem for quite some time now, and can't solve it.
I have the following JSON string:
{"Search":[{"Title":"somestring","Year":"somestring","imdbID":"somestring"}]}, {"Title":"somestring","Year":"somestring","imdbID":"somestring"} etc
The string can repeat itself multiple times, so I want to store the values in a list. In order to do this I've created the following two classes:
The SuggestionListener class:
[DataContract]
class SuggestionLister
{
public List<MovieResults> suggestionlist {get;set;}
}
Which holds the List I want returned.
And the Movieresults class:
[DataContract]
class MovieResults
{
[DataMember]
public string Title { get; set; }
[DataMember]
public string Year { get; set; }
[DataMember]
public string imdbID { get; set; }
}
Which hold the data that needs to be stored. I tried Deserializing it with the following code:
byte[] data = Encoding.UTF8.GetBytes(resp);
MemoryStream memStream = new MemoryStream(data);
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(SuggestionLister));
SuggestionLister suggestionMovies = (SuggestionLister)serializer.ReadObject(memStream);
Where the 'resp' variable is the JSON string. However, when I try this code the suggestMovies object remains null. What is wrong?
Okay so there are a couple of issues:
[DataContract]
public class SuggestionLister
{
[DataMember]
public List<MovieResults> Search { get; set; }
}
You do not have DataMember attribute on your list property and it needs to match the name of the array value which is "Search".
Edit: I tested all of this using your code. Also the format of your JSON that you posted is not correct, but I am assuming that is a pasting error.
Try
[DataContract]
class SuggestionLister
{
public List<MovieResults> Search {get;set;}
}
Since your json seems to be of this format:
{
"Search": [ { "Title": ... }]
}

Parsing JSON data in C#

I have a JSON data as follows
{"id": "367501354973","from": {
"name": "Bret Taylor",
"id": "220439" }
which is returned by an object(result) of IDictionary[String, Object]
In my C# code:
I have made a class for storing the JSON value which is as follows
public class SContent
{
public string id { get; set; }
public string from_name { get; set; }
public string from_id { get; set; }
}
My main C# function which stores the parses the JSON data and stores the value inside the class properties is as follows:
List<object> data = (List<object>)result["data"];
foreach (IDictionary<string, object> content in data)
{
SContent s = new SContent();
s.id = (string)content["id"];
s.from_name = (string)content["from.name"];
s.from_id = (string)content["from.id"];
}
When i execute this code, i get an exception saying System cannot find the Key "from.name" and "from.id"
When i comment the two lines (s.from_name = (string)content["from.name"];s.from_id = (string)content["from.id"];) my code runs fine.
I think i am not able to refer the nested JSON data properly.
Can anyone just validate it and please tell me how to refer nested data in JSON in C#?
Thanks
I'm not sure how you are parsing the JSON string. Are you using a class in the Framework to do the deserialization?
You could use the JavaScriptSerializer Class defined in the System.Web.Script.Serialization Namespace (you may need to add a reference to System.Web.dll)
Using that class, you would write your code like this:
public class SContent
{
public string id { get; set; }
public SFrom from { get; set; }
}
public class SFrom
{
public string name { get; set; }
public string id { get; set; }
}
Then deserialization looks like this:
var json = new JavaScriptSerializer();
var result = json.Deserialize<SContent>(/*...json text or stream...*/);
See JavaScriptSerializer on MSDN. You might also want to check out this similar question.

Categories