Deserialization of Json without name fields - c#

I need to deserialize the following Json, which according to Jsonlint.com is valid, but ive not come across this before or cannot find examples of similar Json and how to deal with it?
[1,"Bellegrove / Sherwood ","76705","486","Bexleyheath Ctr",1354565507000]
My current system with like this:
Data class:
[DataContract]
public class TFLCollection
{ [DataMember(Name = "arrivals")]
public IEnumerable<TFLB> TFLB { get; set; }
}
[DataContract]
public class TFLB
{
[DataMember]
public string routeName { get; set; }
[DataMember]
public string destination { get; set; }
[DataMember]
public string estimatedWait { get; set; }
}
Deserializer:
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(TFLCollection));
using (var stream = new MemoryStream(Encoding.Unicode.GetBytes(result)))
{ var buses = (TFLCollection)serializer.ReadObject(stream);
foreach (var bus in buses.TFLBuses)
{
StopFeed _item = new StopFeed();
_item.Route = bus.routeName;
_item.Direction = bus.destination;
_item.Time = bus.estimatedWait;
listBox1.Items.Add(_item);
My exsiting deserializer works with a full Json stream and iterates through it, but in my new Json I need to deserialize, it only have 1 item, so I wont need to iterate through it.
So is it possible to deserialize my Json example using a similar method than I currently do?

I would say that you are attempting to overcomplicate things. What you have is a perfectly formed json array of strings. If I were you I would deserialize that to an .net array first, and then write a 'mapper' function to copy the values across:
public TFLB BusRouteMapper(string[] input)
{
return new TFLB {
Route = input[x],
Direction = input[y],
};
}
And so on. Of course this assumes that you know what order your json is going to be in, but if you are attempting this in the first place then you must do!

Related

serialization issue with json structure using newtonsoft

This is an old application (.Net 4.5).
I am following the guide here: https://weblog.west-wind.com/posts/2012/aug/30/using-jsonnet-for-dynamic-json-parsing
My goal is to have a way to store a flexible json structure without tying it down to a static structure. For example, in the TriggerJson below, the actual Trigger field is of type string, which is supposed to be json. That json structure could reflect ExpiryTriggerJson, or some other structure which is determined by TriggerType.
I have the following structure:
public class TriggerJson
{
public string TriggerType { get; set; }
public string ConfiguredBy { get; set; }
public string Trigger { get; set; }
}
public class ExpiryTriggerJson
{
public string ActionType { get; set; }
public TriggerRecipient[] Recipients { get; set; }
}
public class TriggerRecipient
{
public string Id { get; set; }
public string Name { get; set; }
public bool IsTag { get; set; }
}
In the following code, I am creating a list of TriggerJson such that each element's Trigger field be a json structure made from ExpiryTriggerJson object:
var tjList = new List<TriggerJson>();
var triggerJson = new TriggerJson();
triggerJson.TriggerType = TriggerJsonHelper.ExpiryTriggerType;
triggerJson.Trigger = JsonConvert.SerializeObject(new ExpiryTriggerJson
{
Recipients = taskRecipients,
ActionType = TriggerJsonHelper.ExpiryTriggerActionType_Task
});
triggerJson.ConfiguredBy = configuredBy;
tjList.Add(triggerJson);
fieldValue.TriggersJson = JsonConvert.SerializeObject(tjList);
This creates the following structure for example where Trigger field reflects a serialized structure which has escaped double quotes due to double serialization:
[{"TriggerType":"ExpiryTrigger","ConfiguredBy":"acd1ac353ac44e078aaef8ce6479a4c6","Trigger":"{\"ActionType\":\"CreateReminderTask\",\"Recipients\":[{\"Id\":\"70050a95-f31b-41b7-9b49-0688fa76dba5\",\"Name\":\"blah blah\",\"IsTag\":false}]}"}]
This creates a problem for me when trying to deserialize this data later on when reading it back:
JArray jsonObj = JArray.Parse(triggersJson);
foreach (dynamic obj in jsonObj)
{
if (obj.TriggerType == ExpiryTriggerType)
{
ExpiryTriggerJson triggerData = obj.Trigger.ToObject<ExpiryTriggerJson>();
The above code tries to parse back ExpiryTriggerJson structure that was first assigned to the field Trigger of TriggerJson element. This throws a runtime deserialization exception when executing the last line trying to convert to ExpiryTriggerJson which I suspect happens due to double deserialization.
My question is how do I accomplish my goal of storing static/structural json data as a string and then parse it back in a nested manner?
This might be what you want.
public dynamic Trigger {get;set;}
Then trigger will be resolved to whatever type it receives at runtime.

C# serialize JSON without property name

maybe this was asked somewhere before, but I don't know how to search for my problem.
I'm using a WebAPI to verify licenses. From this API I get the return JSON string in follwing format.
string json = "[{"status":"error","status_code":"e002","message":"Invalid licence key"}]"
This is my serializer
using (var ms = new MemoryStream(Encoding.Unicode.GetBytes(json)))
{
DataContractJsonSerializer js = new DataContractJsonSerializer(typeof(ActivationResponseWooSl));
ActivationResponseWooSl ar = (ActivationResponseWooSl)js.ReadObject(ms);
}
Now my questions is, how must the "ActivationResponseWooSl" class look like so that the serializer can convert it?
Any help is highly appreciated!
For now it looks like that (what's not workiing):
[DataContract]
public class ActivationResponseWooSl
{
[DataMember(Name = "status")]
public string Status { get; set; }
[DataMember(Name = "status_code")]
public string ErrorCode { get; set; }
[DataMember(Name = "message")]
public string ErrorMessage { get; set; }
}
However when I serialize my json string, all properties are "null".
Your class is correct. Your JSON is an array of object.
Try
DataContractJsonSerializer js = new DataContractJsonSerializer(typeof(ActivationResponseWooSl[]));
var arr = (ActivationResponseWooSl[])js.ReadObject(ms);

UWP C# - How to deserialize JsonObject into a class using Windows.Data.Json?

I don't want to use Newtonsoft's Json.Net library. I'm avoiding any third-party dependencies if I can help it in this project.
If I have JSON that looks like this:
{
"has_more_items": false,
"items_html": "...",
"min_position": "1029839231781429248"
}
and I have a class that looks like this:
public class TwitterJson
{
bool hasMore { get; set; } // has_more_items
string rawText { get; set; } // items_html
string nextKey { get; set; } // min_position
}
and I have a JsonObject containing the above JSON:
JsonObject theJson = JsonObject.Parse(result);
How do I deserialize the JsonObject into my class? I've been trying to find a clear example of this, and everything I've found uses Json.Net.
I've been trying to find a clear example of this, and everything I've found uses Json.Net.
Because reinventing existing functionality is a waste of time especially when all the hard work has already been done for you.
If you insist on not using it then you will have to manually construct the object model based on the expected JSON.
For example, assuming publicly available properties
public class TwitterJson {
public bool hasMore { get; set; } // has_more_items
public string rawText { get; set; } // items_html
public string nextKey { get; set; } // min_position
}
Then parsing the above to the desired object model
JsonObject theJson = JsonObject.Parse(result);
var model = new TwitterJson {
hasMore = theJson.GetNamedBoolean("has_more_items"),
rawText = theJson.GetNamedString("items_html"),
nextKey = theJson.GetNamedString("min_position")
};
As mentioned by #Dimith, you need to decorate your class with [DataContract] and [DateMember], Please refer to below code which will convert your JSON into a given object.
// Deserialize a JSON string to a given object.
public static T ReadToObject<T>(string json) where T: class, new()
{
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(json)))
{
return ser.ReadObject(stream) as T;
}
}
Class:
[DataContract]
public class TwitterJson
{
[DataMember(Name = "has_more_items")]
bool hasMore { get; set; } // has_more_items
[DataMember(Name = "items_html")]
string rawText { get; set; } // items_html
[DataMember(Name = "min_position")]
string nextKey { get; set; } // min_position
}
Sample on how to use:
var result = "{\"has_more_items\": false, \"items_html\": \"...\",\"min_position\": \"1029839231781429248\"}";
var obj = ReadToObject<TwitterJson>(result);
You have to decorate your class with [DataContract] and [DataMember] attributes. Write the json into a memory stream and deserialize using DataContractJsonSerializer
Here is a more elaborated sample.
In addition to #Nkosi's answer below are some Comparisons between JSON.net and other alternatives:
JSON.Net vs DataContractJsonSerializer
JSON.Net vs Windows.Data.Json

Array JSON deserialize

I'm trying to get the data from a website RSS converting it to JSON. I got this JSON string:
http://ajax.googleapis.com/ajax/services/feed/load?v=1.0&q=http%3A%2F%2Frss.tecmundo.com.br%2Ffeed
I'm using lists to get the values but I got this error "Cannot create an instance of the abstract class or interface" and I don't know how to solve it. It happens in this line.
IList<News> content = new IList<News>();
Here is my code.
public class News
{
public string author { get; set; }
public string title { get; set; }
public string content { get; set; }
public string contentSnippet { get; set; }
public string link { get; set; }
public string publishedDate { get; set; }
public string[] getFeed(string Website)
{
string path = #"http://ajax.googleapis.com/ajax/services/feed/load?v=1.0&q=" + Website;
var json = new WebClient().DownloadString(path);
JObject jsonObject = JObject.Parse((string)json);
IList<JToken> jsonData = jsonObject["responseData"]["feed"]["entries"]["0"].Children().ToList();
IList<News> content = new IList<News>();
foreach(JToken data in jsonData)
{
News finalData1 = JsonConvert.DeserializeObject<News>(jsonData.ToString());
content.Add(finalData1);
}
return new string[] { "I must return something here." };
}
}
Here is the tool I'm using to visualize better the JSON string: http://jsonschema.net/#/
The error you're getting has nothing to do with JSON. It is because you're trying to create an instance of an interface. You could just fix that by giving it the concrete List<T> class:
IList<News> content = new List<News>();
However, the simpler way of converting the IList<JToken> to an IList<News> is probably to use LINQ again - you can do all of this in one step pretty easily:
IList<News> content = jsonObject["responseData"]["feed"]["entries"]["0"]
.Children()
.Select(token => JsonConvert.DeserializeObject<News>(token.ToString())
.ToList();
That compiles, but isn't actually want due to the data you've got. entries is an array, so you probably want:
JArray array = (JArray) jsonObject["responseData"]["feed"]["entries"];
var content = array
.Select(token => JsonConvert.DeserializeObject<News>(token.ToString())
.ToList();
Your problem has nothing to do with the json, but with trying to create an instance of an interface which is not possible in c#. You need to create an instance of a concrete class that implements the IList interface. List would be one example. There are others, including arrays.

Retrieving data from an Object(deserialized json) in C#

I have a JSON string that I am trying to parse, using C#. I have used JsonConvert to serialize my data into a JSON string.
Here is my sample JSON string:
{"names": ["John", "Joe", "Jack"], "nationality": "American"}
I am able to deserialize this string into an object using JsonConvert.DeserializeObject(x);
The problem is, I dont know how to read from the object, using C#. Can someone help me out?
public class People
{
[JsonProperty("names")]
public List<string> Names;
[JsonProperty("nationality")]
public string Nationality;
}
Other answers are technically correct, but using JsonPropertyAttribute is a universally accepted convention. Then use JsonConvert:
var people = JsonConvert.DeserializeObject<People>(x);
A better approach would be to define a class with the expected structure, then using JavaScriptSerializer to deserialize it:
class NameSet
{
public IList<string> names { get; set; }
public string nationality { get; set; }
}
var serializer = new JavaScriptSerializer();
var nameset = serializer.Deserialize<NameSet>(jsonString);
Create a custom class like this:
public class CustomData
{
public string[] Names { get; set; }
public string Nationality { get; set; }
public CustomData() { }
}
And use JsonConvert to deserialize yo an object of this type:
CustomData data = JsonConvert.DeserializeObject<CustomData>(x);
The following should suffice:
public class PeopleGroup {
public string[] names { get; set; }
public string nationality { get; set }
}
var myObject = JsonConvert.DeserializeObject<PeopleGroup>(x);
Basically, you create a strongly typed object, and deserialise directly into it.
If you don't want to actually define a class, you can use an anonymous type:
string json = "{\"names\": [\"John\", \"Joe\", \"Jack\"], \"nationality\": \"American\"}";
// Just defining the structure of the anonymous type
var x = new { names = new string[0], nationality = string.Empty };
x = JsonConvert.DeserializeAnonymousType(json, x);
You should use dataContractJsonSerializer class, it is faster and most important is it is inbuilt class of .Net Framework. I will post solution in my next commment, in that How can we use DataContractJsonSerializer class.Now I cant post solution because in my end net is too slow :(, but I will post today.

Categories

Resources