New to JSON.net, sample code - c#

Im starting a new WP7 app that gets information from a DNLA server. The server supports JSON languages for the REST protocol. I did some research and found json.net was very well recommended.
I can get data by using http://192.168.1.1:234/rest/status?media=json
Giving me:
{"serverStatus":"STARTED","renderers":[{"uuid":"00a0965fa15c","ipAddress":"192.168.1.10","name":"KDL-52NX803","profileId":"9","status":"ACTIVE"},{"uuid":"1829220b083f","ipAddress":"192.168.1.13","name":"Windows Media Player","profileId":"1","status":"INACTIVE"},{"uuid":"5d70ac53cf8e","ipAddress":"192.168.1.14","name":"Unrecognized device","profileId":"1","status":"UNKNOWN"},{"uuid":"60465a95eec4","ipAddress":"192.168.1.22","name":"Playstation 3","profileId":"4","status":"UNKNOWN"},{"uuid":"001dd860bce4","ipAddress":"192.168.1.9","name":"Xbox 360","profileId":"3","status":"INACTIVE"}]}
Im very much new to c#, ive read the official Json.NET documenation, but would prefer to see sample code to get me moving.
I have created listbox to collect "renderers" data, and TextBlock for the current "serverStatus" of the server.
If anyone can help and would very much appreciate your efforts

For starters, http://json2csharp.com/ is handy for putting in your json and creating a poco.
public class Renderer
{
public string uuid { get; set; }
public string ipAddress { get; set; }
public string name { get; set; }
public string profileId { get; set; }
public string status { get; set; }
}
public class RootObject
{
public string serverStatus { get; set; }
public Renderer[] renderers { get; set; }
}
This page has simple examples on serialize/dserialize.
RestSharp is a wonderful HTTP API Client that supports WP7. It will deserialzie for you and also allows you to implement your own serializer/deserializer.

Related

Adding run-time only collection to OData list

I'm new to OData and I have a working solution for complex requests of my domain data, which is great. The bit I'm looking for help with is using this data and sending the entire list to another API to append additional data to the OData response for a particular object type.
I don't mind losing the ability to further query the appended collection, this can be done later in my front end. I'm looking for some help in identifying the right architecture for my solution.
I've seen a few possible answers that would be to create a custom serializer or use AutoMapper to populate the DTO but this would send the requests to the other API one at a time. I'm looking to send the entire list as the performance is improved rather than one at a time as there can be 20,000+ items in the response.
Here's my current schema.
Domain
public class InventoryItem
{
public virtual Guid Id { get; set; }
public virtual string Name { get; set; }
public virtual string DeviceName { get; set; }
}
DTO
public class InventoryItem
{
public virtual Guid Id { get; set; }
public virtual string Name { get; set; }
public virtual string DeviceName { get; set; }
public IList<ReadingDto> Readings { get; set; } = new List<ReadingDto>();
}
public class ReadingDto
{
public double? Value { get; set; }
}
As the ReadingDto is obtained from another API, this shouldn't be present in my domain model. It would never be populated.
The ideal solution would be to utilise a service within my project which would send the list over to the other API whilst maintaining the flexibility of using OData. Whether this is in a custom serializer, middleware or filters, I'm just not sure what would be best.

Deserialize string Property as Json Object in Azure Modile App Service Backend

I'm having a similar problem as posted here
Except I'm using an Azure Mobile App Service Backend.
I have json string stored in the sql database and I need the App Service to de-serialize it to the object type.
Currently the Json from the Azure Mobile App Service Get looks like this:
(and this isn't the in-code formatting, it's actually formatting the json that way)
{"deleted": false,"updatedAt": "2020-06-09T16:30:48.09Z","createdAt": "2020-06-03T04:34:41.617Z","version": "AAAAAABXrYA=","id": "DBEC6DE9-3C5C-47C5-8404-67C79FCF6740","equipmentSpeakerTapValue": "{\"value\": 0.0,\"wattage\": 0,\"direct\": false}"}
equipmentSpeakerTapValue is shown as a string an not a json nested object
I need the Json to look like this:
{"deleted": false,"updatedAt": "2020-06-09T16:30:48.09Z","createdAt": "2020-06-03T04:34:41.617Z","version": "AAAAAABXrYA=","id": "DBEC6DE9-3C5C-47C5-8404-67C79FCF6740","equipmentSpeakerTapValue":{"Value":2.5,"Wattage":70,"Direct":false}"}
Since I'm using Azure Mobile App Service I don't know if the problem is with the Entity Framework or the Json Serializing/DeSerializing. I also don't know how to change it since Azure Mobile App Service is a wrapper so you can't do things normally.
Here is my EF object model and the model of what I need the string property to deserialize to:
public class SiteEquipment
{
public string Id { get; set; }
public byte[] Version { get; set; }
public DateTimeOffset? CreatedAt { get; set; }
public DateTimeOffset? UpdatedAt { get; set; }
public bool Deleted { get; set; }
//I don't know which EquipmentSpeakerTapValue to use:
//string version that serializes to: "equipmentSpeakerTapValue": "{\"value\": 0.0,\"wattage\": 0,\"direct\": false}"
public string EquipmentSpeakerTapValue { get; set; }
//object version that should serialize to: "equipmentSpeakerTapValue":{"Value":2.5,"Wattage":70,"Direct":false}"
public TapValue EquipmentSpeakerTapValue { get; set; }
}
public class TapValue
{
public double Value { get; set; }
public int Wattage { get; set; }
public bool Direct { get; set; }
}
sorry I can't comment yet.
I noticed in your second string you only capitalized the last 3 "items" in the json. Do you not care if the previous are capped?
Your String Above
{"deleted": false,"updatedAt": "2020-06-09T16:30:48.09Z","createdAt": "2020-06- 03T04:34:41.617Z","version": "AAAAAABXrYA=","Id": "DBEC6DE9-3C5C-47C5-8404-67C79FCF6740","equipmentSpeakerTapValue":{"Value":2.5,"Wattage":70,"Direct":false}"}
Verification Question String
{"Deleted": false,"UpdatedAt": "2020-06-09T16:30:48.09Z","CreatedAt": "2020-06-03T04:34:41.617Z","Version": "AAAAAABXrYA=","id": "DBEC6DE9-3C5C-47C5-8404-67C79FCF6740","EquipmentSpeakerTapValue":{"Value":2.5,"Wattage":70,"Direct":false}"}
I am actually surprised your first values, such as updatedAt get deserialized properly.
What I would do is in your class definitions, add the JsonProperty attribute so that json knows to deserialize the non-backed parameter (such as Wattage doesn't have a private wattage property)
So put
public class TapValue
{
[JsonProperty("value")]
public double Value { get; set; }
[JsonProperty("wattage")]
public int Wattage { get; set; }
[JsonProperty("direct")]
public bool Direct { get; set; }
}
Are you using Newtonsoft? Because the above would tell it to map the lower case versions to the Upper case versions. Or if you had MyValueHere, you might have myValueHere in json, so make that your jsonproperty value myValueHere and it will map to MyValueHere

DataContract Serializer and Json.Net When using object that contains property of type XmlElement

We currently have an object what we are using to pass around information about incoming API calls of of the properties is the message itself. The message property is an XmlElement and the DataContract serializer is happy to do it's thing with an XmlElement.
We are no adding on to our API and these web services are making RPC via SignalR to hosted clients across the united states. What I have found is that the Json.Net library is not happy with an XmlElement I get the following message "Xmlnodeconverter only supports deserializing xml document". Okay fine so I'll use an XmlDocument then and get around this problem... But wait the DataContract Serailizer isn't happy with an XmlDocument. It seems to be a situation where I cant have my cake and eat it too. If I go with XmlDocument the SignalR client is happy but the rest of the applications are not, and if I use a XmlElement the SignlR client can't recive the message.
Note: the SignalR client is a self hosted windows service not javascript.
So what I want to know is. Is there a way to either get Json.net to except XmlElement or the DataContract Serializer to except XmlDocument. It would be much simpler for us to change the SignalR side of things as this is new and the rest of the applications alrady understand the XmlElement.
Here is the object that contains the XmlElement:
[DataContract(Name = "AuditData")]
public class AuditData
{
[DataMember]
public XmlElement Message { get; set; }
[DataMember]
public XmlDocument MessageV2 { get; set; }
[DataMember]
public IList<ErrorMessage> Errors { get; set; }
[DataMember]
public string DealerCode { get; set; }
[DataMember]
public DateTime Time { get; set; }
[DataMember]
public IntegrationTransactionTypeEnum TransationType { get; set; }
[DataMember]
public string BooksAccountNumber { get; set; }
[DataMember]
public IntegrationStepIdEnum Step { get; set; }
[DataMember]
public IntegrationErrorLevelEnum? ErrorLevel { get; set; }
[DataMember]
public IEnumerable<Criteria> Search { get; set; }
}

Parsing JSON with shortened keys in C#

I'm porting a project from Android to Windows Phone 8 and can't find any info on how to specify which JSON key maps to which object field.
The Android code uses Google GSON and the SerializedName annotation to map em in the JSON to the email field in the object.
I'm also controlling which fields are [de]serialized using the Expose annotation. How would I go about doing these same things in my Windows Phone 8 project?
I'd absolutely hate to use a class that looks like this:
public sealed class SomeData
{
public string em { get; set; }
public string un { get; set; }
public string fn { get; set; }
public int tz { get; set; }
}
Thanks.
You can mark properties with DataMember attribute to explicitly specify desired name.
[DataMember(Name = "em")]
public string Email { get; set; }

Modelling a NoSQL Forum Application with C# / ASP.net MVC

I'm currently developing a Forum (Question / Answer) based application.
Using C# ASP.net MVC and MongoDB for data storage.
I'm currently looking at the model.
I was thinking of having separate classes like this: (simplified)
public class Question
{
public string ID { get; set; }
public string Title { get; set; }
public string Body { get; set; }
public List<string> Tags { get; set; }
public DateTime DateCreated { get; set; }
public string ForumID { get; set; }
}
Answer
public class Answer
{
public string ID { get; set; }
public string QuestionID { get; set; }
public string Body { get; set; }
public DateTime DateCreated { get; set; }
}
My questions is:
How to handle the "replies"
Am I best of having (as in the model above) two separate "entities"
Or should I have a List of Answer in my Question model?
Some requirements are that i'll need to be able to display a count of answers etc...
With this being stored in a NoSQL db, I'm aware I should denormalize things, but how can I insert an answer, without retrieving the entire post? Is that sort of operation possible using NoRM with MongoDB?
Normally in MongoDB, you would embed the answers inside the question. 99% of the time you're going to query by Question, so you might as well get the Answers at the same time.
Some requirements are that i'll need to be able to display a count of answer...
If you're bringing back the answers with the questions, this is really easy. You'll have an array/list/collection with answers. So you'll just grab the length.
but how can I insert an answer, without retrieving the entire post
MongoDB supports an atomic "$push" operation. That means that you can add an item to an array without actually loading the document from the client. From the javascript shell, it would look like this:
db.questions.update( {_id : your_id}, { $push : { answers : your_answer_object } } );
So MongoDB is capable of this. You'll have to check with the NoRM drivers to ensure that they actually allow for this type of behavior (they're really missing something if they don't support $push).
Answer should be part of the question.
public class Question
{
public string ID { get; set; }
public string Title { get; set; }
public string Body { get; set; }
public List<string> Tags { get; set; }
public DateTime DateCreated { get; set; }
public string ForumID { get; set; }
public List<Answers> Answers { get; set; }
}
Because of the lack of joins document databases encourage you to store instances of the entire graph in one document.

Categories