How to Deserialize specific JSON string - c#

I've been trying to deserialize a specific JSON string using the JavaScriptSerializer class for a day now without success.
I've read a fair few posts on here, but cant find one that addresses a JSON string similar in design to the one I need to use, so I'm asking my own.
The string I need to deserialize is as follows:
["SomeName",[["alpha","bravo"],[1,6]],[["John","Bob","Paul","Ringo"],[1,2,1,8]]]
I thought this class would solve it, but I was evidently wrong:
[Serializable]
internal class OuterDeserializedObj
{
[Serializable]
internal class InnerDeserializedObj
{
public string Name { get; set; }
public List<List<string>> Array1 { get; set; }
public List<List<string>> Array2 { get; set; }
}
public List<InnerDeserializedObj> innerObj { get; set; }
}

Your Json is just an array (array of array of array of objects), Therefore the only way i can think of is to create a similar structure in c#.
(Using Json.Net)
string json = #"[""SomeName"",[[""alpha"",""bravo""],[1,6]],[[""John"",""Bob"",""Paul"",""Ringo""],[1,2,1,8]]]";
var arr = JArray.Parse(json);
string name = (string)arr.OfType<JValue>().First();
var arrays = arr.OfType<JArray>()
.Select(x => x.Select(y=>y.Select(z=>(string)z)
.ToList())
.ToList())
.ToList();

Related

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.

Deserialize an inner array to objects using JSON.net

An existing JSON-based web-service returns a fairly messy JSON object, where all the useful data is contained in the elements of an array which is itself the content of a 1-element array. Something like this (I'm anonymising it, hopefully no typos):
{"rows":[[
{"name":"John","time":"2016-03-20 01:00:00","id":"2","code":"1234"},
{"name":"Sam","time":"2016-03-20 01:00:00","id":"24","code":"999"},
{"name":"Paul","time":"2016-03-20 01:00:00","id":"12","code":"6512"}
]]}
Using JSON.net I need to access each of those row sub-elements but I'm not sure how to iterate over this and if I should be deserializing to a concrete type or just reading the raw data from my json object.
The data will be aggregated inside a method so the 'type' of each row is not something that needs to be known outside the method.
rows will always be a 1-element array containing an array of elements as shown.
#Fals's solution should work well, but if you want to do away with the RootObject, you can use Json.Net's LINQ-to-JSON API to parse the JSON and get the data into a simple list of items that is easy to work with.
Assuming you have a class defined for the item data like this:
public class Item
{
public string name { get; set; }
public DateTime time { get; set; }
public string id { get; set; }
public string code { get; set; }
}
Then you can do this to get your list of items:
List<Item> items = JObject.Parse(json)["rows"][0]
.Select(jt => jt.ToObject<Item>())
.ToList();
Fiddle: https://dotnetfiddle.net/FtB3Cu
If you want to avoid declaring any classes at all and instead use an anonymous type, you can change the code to this:
var items = JObject.Parse(json)["rows"][0]
.Select(jt => new
{
name = (string)jt["name"],
time = (DateTime)jt["time"],
id = (string)jt["id"],
code = (string)jt["code"]
})
.ToList();
Fiddle: https://dotnetfiddle.net/0QXUzZ
It's simple, your root object contains a List<List<>>:
Your object should look like:
public class InnerObject
{
public string name { get; set; }
public DateTime time { get; set; }
public string id { get; set; }
public string code { get; set; }
}
public class RootObject
{
public List<List<InnerObject>> rows { get; set; }
}
Then use JSON.NET:
string json = #"{'rows':[[
{'name':'John','time':'2016-03-20 01:00:00','id':'2','code':'1234'},
{'name':'Sam','time':'2016-03-20 01:00:00','id':'24','code':'999'},
{'name':'Paul','time':'2016-03-20 01:00:00','id':'12','code':'6512'}
]]}";
var rootObject = JsonConvert.DeserializeObject<RootObject>(json);
By the way, this site json2csharp can generate the C# class from JSON, makes the life ease :)
EDIT:
You can also use dynamic, and then avoid the parser from the `RootObject:
var rootObject = JsonConvert.DeserializeObject<dynamic>(json);
rootObject.rows[0] <--- should have what you need

Deserializing json - wrong type

Here's how I try to deserialize my json:
new JavaScriptSerializer().Deserialize<Dictionary<int, MyModel>>(myData);
Here's the class:
public class MyModel
{
public Dictionary<int, ItemModel> Translation { get; set; }
public int Id { get; set; }
}
public class ItemModel
{
public string Name { get; set; }
public string ShortDescription { get; set; }
public string LongDescription { get; set; }
}
And here's the json:
"[[],[],{"Translation":{"1":{"Name":"Bla1","ShortDescription":"bla1","LongDescription":"bla1"},"2":{"Name":"BlaUS1","ShortDescription":"BlaUS1","LongDescription":"BlaUS1"}},"Id":"12"},{"Translation":{"1":{"Name":"Bla22","ShortDescription":"bla22","LongDescription":"bla22"},"2":{"Name":"Bla2US2","ShortDescription":"Bla2US2","LongDescription":"Bla2US2"}},"Id":"13"}]"
and I get the error that the type is not supported for deserialization of an array.
Where is my error?
First of all your JSON looks a bit wrong to me. It is and array of 4 elements and 1st two elements are empty arrays but other two objects? I suspect your JSON should be something like that:
"[{"Translation":{"1":{"Name":"Bla1","ShortDescription":"bla1","LongDescription":"bla1"},"2":{"Name":"BlaUS1","ShortDescription":"BlaUS1","LongDescription":"BlaUS1"}},"Id":"12"},{"Translation":{"1":{"Name":"Bla22","ShortDescription":"bla22","LongDescription":"bla22"},"2":{"Name":"Bla2US2","ShortDescription":"Bla2US2","LongDescription":"Bla2US2"}},"Id":"13"}]"
Another issue is that you have Dictionary<int, ItemModel> but for serialization/deserialization you must have key of String or Object type.
Working example (providing that you changed from Dictionary<int, ItemModel> to Dictionary<object, ItemModel>):
string input = "[{\"Translation\":{\"1\":{\"Name\":\"Bla1\",\"ShortDescription\":\"bla1\",\"LongDescription\":\"bla1\"},\"2\":{\"Name\":\"BlaUS1\",\"ShortDescription\":\"BlaUS1\",\"LongDescription\":\"BlaUS1\"}},\"Id\":\"12\"},{\"Translation\":{\"1\":{\"Name\":\"Bla22\",\"ShortDescription\":\"bla22\",\"LongDescription\":\"bla22\"},\"2\":{\"Name\":\"Bla2US2\",\"ShortDescription\":\"Bla2US2\",\"LongDescription\":\"Bla2US2\"}},\"Id\":\"13\"}]";
List<MyModel> myModels = new JavaScriptSerializer().Deserialize<List<MyModel>>(input);
Your string suggests that what you have is a JSON array, eg:- [1,2,3]
but you are trying to deserialize it into a dictionary for which the json representation is akin to
{"1":"Hai","2":"Hello"}
obviously the library is throwing an error. May be why dont you use the following to deserialize the string.
new JavaScriptSerializer().Deserialize<List<MyModel>[]>(myData)
However, to use it you can't have empty arrays in the json, you have to fill them with default values for the properties.
To prove that the above works, try
"[{"Translation":{"1":{"Name":"Bla1","ShortDescription":"bla1","LongDescription":"bla1"},"2": {"Name":"BlaUS1","ShortDescription":"BlaUS1","LongDescription":"BlaUS1"}},"Id":"12"},{"Translation":{"1":{"Name":"Bla22","ShortDescription":"bla22","LongDescription":"bla22"},"2":{"Name":"Bla2US2","ShortDescription":"Bla2US2","LongDescription":"Bla2US2"}},"Id":"13"}]"
with
new JavaScriptSerializer().Deserialize<List<MyModel>>(myData)

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

Deserialise JSON with random key

I am accessing an API which is returning JSon in the format:
{"status":1,"complete":1,"list":{"293352541":{"item_id":"293352541","fave":"0"},"247320106":{"item_id":"247320106","fave":"0"},"291842735":{"item_id":"291842735","fave":"0"} .....
The problem I am having is with the number before the item_id tag. It is breaking any attempt I make at deserialising as I cannot represent this random integer in an object that I deserialise in to.
I would expect this number to be, for example, the word "Item", so that it is key representing the enclosed object, but having this number means I cannot make an object representation of the JSon.
So
public class MyClass
{
public string status { get; set; }
public string complete { get; set; }
public List<MyObject> list { get; set; }
}
public class MyObject
{
public string item_id { get; set; }
public string fave { get; set; }
}
then
var items = new JavaScriptSerializer().Deserialize<MyClass>(jsontext);
dersialises, but items.list is empty.
Also,
dynamic result = JSon.Parse(jsontext);
works, but I cannot deserialise or access the list of items in a nice way.
Is there any way to do this? thanks
Because it doesn't require predefined types to deserialize into, you can do this with json.net (also available with nuget). For instance:
var jObj = JObject.Parse(data);
var sense = jObj["list"]
.Select(x => (JProperty)x)
.Select(p => new {
propName = p.Name,
itemId = p.Value["item_id"],
fave = p.Value["fave"]});

Categories