Null value after json deserialization on windows phone - c#

I am using the Json.DeserializeObject method in windows phone, inorder to deserialize json, the problem I am having is one of the variable names, in the json has a space and I just can't get it to deserialize. it returns a null the whole time, and if I view the raw json it does contain a value
part of raw json:
\"Service Provider\":Test\"
When I try to generate a class for the json into which it needs to be deserialized, the Service Provider section tells me "Invalid Name" and that obviously doesn't work in C# as a variable name, but I believe the variable name can be anything:
public string __invalid_name__Service Provider { get; set; }
current code:
public string Service_Provider { get; set; }

Using Json.Net, Just decorate your property with "JsonProperty" Attribute
string json = #"{""Service Provider"":""Test""}";
var obj = JsonConvert.DeserializeObject<TempObject>(json);
public class TempObject
{
[JsonProperty("Service Provider")]
public string ServiceProvider;
}

Related

serialize mongoDB document with ObjectID id back after JSON conversion

I have this C# object type:
public class MyClass
{
[BsonRepresentation(BsonType.ObjectId)]
public ObjectId id { get; set; }
public string myString { get; set; }
}
My backend (C#) gets a document of this type from MongoDB and returns it to my frontend client (JS) which modifies its property (myString) and then sends it back to backend in the body of an HTTP POST Request, but I can't convert it back to MyClass...
I tried this:
string incomingRequest = await new StreamReader(req.Body).ReadToEndAsync();
var test = Newtonsoft.Json.JsonConvert.DeserializeObject<MyClass>(incomingRequest);
// or "MyClass test = ..."
=> Error converting value \"60b903b87c309bb60f88adc6\" to type 'MongoDB.Bson.ObjectId
and this:
string incomingRequest = await new StreamReader(req.Body).ReadToEndAsync();
var test = MongoDB.Bson.Serialization.BsonSerializer.Deserialize<MyClass>(incomingRequest);
// or "MyClass test = ..."
=> Element 'id' does not match any field or property of class MyProject.Models.Myclass.
The problem is that the frontend (JS) converts id's type from ObjectId to string, but I'm not sure how to change that back to ObjectId in backend. If I change MyClass.id type to string, the problem is solved, but I read that the performance much better when using ObjectId instead of string.
Any idea? :(

Change Datamember name dynamically for a parameter (includes $ in parameter name)

I have a problem where i need to output an object from a wcf restful service with a $ in it. I've tried outputting a dictionary but when that serializes to JSON the $gets encoded. The service i am communicating with requires the object to look like this [{$name : value}]
Is it possible to change the Name in the data member attribute on a parameter at runtime?
[DataMember(Name = "RenameMe")]
public string Values { get; set; }
public Variable(string name, string values)
{
this.Values = values;
[set the name attribute to : "$name"]
}

Sending C# Reserved Word as Property of PostData Api

I have some JSON that i am sending over to my C# API and it looks like the following
{
"currency": "BTC",
"amount": "0.00049659",
"type": "bankToExchange"
}
The issue is when the model arrives in my controller, the type property is changed to #type which is making the post request fail.
The API I am trying to connect to uses type, so this cannot be changed. The post works in Postman, so is there a work around for this?
Add the DataMember name property on your type using JsonProperty:
[DataMember(Name = "#type")] //if not using NewtonSoft
[JsonProperty("#type")] //if using NewtonSoft
public string type { get; set; }
Use Data member attribute with property name. You can use by creating class for your json, as follows
[DataContract]
public class Sample{
[DataMember(Name = "#type")]
public string Type{get;set;}
}
You can try with another approach as well, which is elegant and more meaning full if you add comment for appending # before property name :
public class Sample{
public string #type{get;set;}
}
For reference: object to deserialize has a C# keyword

Can I consume JSON without defining the fields before in C# code?

I am working on a REST API for a project using Visual Studio 2013 with C# and ASP.NET, and I need some guidance.
When the webpage performs a POST, I am passing along a number of fields as a JSON object. By defining a data transfer object in my C# code, I can easily read the values from the JSON, but only if I define all the fields (with the same name).
Here is my current (working) code:
public class AgencyPostDTO
{
public string AgencyName { get; set; }
public string Address1 { get; set; }
public string Address2 { get; set; }
public string City { get; set; }
public string State { get; set; }
public string ZIP { get; set; }
}
// POST: api/Agency
public string Post(AgencyPostDTO Agency)
{
int success;
success = SQLUpdateAgency(Agency);
if (success < 1)
{
return "Failed";
}
else
{
return "Success";
}
}
So far no problems. I need to pass the data over to a second function, where I will perform some data processing (including converting the data into XML) and send the data/XML to MS SQL using a stored procedure:
public int SQLUpdateAgency(AgencyPostDTO Agency)
{
string xml = Agency.SerializeObject();
... code to call SQL stored procedure ommitted here
}
Now to my problem. I would prefer if I did not have to define the parameters of the data transfer object AgencyPostDTO in the code, and instead the code would just read the incoming JSON and pass it along to the next function, where I create the XML containing everything passed along.
As it works now, if the JSON contains for example an email address field, it will be dropped unless I define it in AgencyPostDTO.
So why do I want to do this? For future ease of maintenance. The users may come and say they want to add additional fields to the web form. I can then simply have our SQL expert add that column to the table, give me the name of it and I add an input field to the HTML form and make sure it is included in the JSON sent over. That way we never have to touch the already written, tested and working code. The new field is simply passed though the whole process.
Can this be done? If so, any suggestions on how?
If you used JSON.NET to handle the deserialisation of your objects then that has support for dynamic properties. Once you'd read your JSON string, you could convert it to a JArray or JObject and from there by using the .Children() call to get a list of all properties to convert it to any XML object you needed.
Have a look here:
Deserialize json object into dynamic object using Json.net

Deserializing JSON when fieldnames contain spaces

I'm writing a tool to read JSON files. I'm using the NewtonSoft tool to deserialize the JSOn to a C# class. Here's an example fragment:
"name": "Fubar",
".NET version": "4.0",
"binding type": "HTTP",
The field names contain spaces and other characters (the .) that are invalid in C# identifiers.
What is the correct way to do this?
(Unfortunately I don't have the option of changing the JSON format.)
Use the JsonProperty attribute to indicate the name in the JSON. e.g.
[JsonProperty(PropertyName = "binding type")]
public string BindingType { get; set; }
System.Text.Json
If you're using System.Text.Json, the equivalent attribute is JsonPropertyName:
[JsonPropertyName(".net version")]
public string DotNetVersion { get; set; }
Example below:
public class Data
{
public string Name { get; set; }
[JsonPropertyName(".net version")]
public string DotNetVersion { get; set; }
[JsonPropertyName("binding type")]
public string BindingType { get; set; }
}
// to deserialize
var data = JsonSerializer.Deserialize<Data>(json);
Not sure why but this did not work for me. In this example I simply return a null for "BindingType" every time. I actually found it much easier to just download the Json result as a string and then do something like:
myString = myString.Replace(#"binding type", "BindingType")
You would do this as the step before deserializing.
Also was less text by a tad. While this worked in my example there will be situations where it may not. For instance if "binding type" was not only a field name but also a piece of data, this method would change it as well as the field name which may not be desirable.
If you want to initialize the Json manually, you can do:
var jsonString = "{" +
"'name': 'Fubar'," +
"'.NET version': '4.0'," +
"'binding type': 'HTTP'," +
"}";
var json = JsonConvert.DeserializeObject(jsonString);
return Ok(json);
Don't forget to include using Newtonsoft.Json;

Categories