Converting JSON to an Object - c#

i have a method that sends a POST Request to my PHP API and the API responds with a JSON String return value.
however after using JsonConvert.DeserializeObject() to the JSON result, i am getting this format
{[
{
"usr_name": "12-34567",
"usr_fullname": "LASTNAME, FIRSTNAME MIDDLENAME",
"usr_emailaddress": "myemail#mail.com",
"photo_url": "http://mywebsite.com/fetch_photo.php?id=MTItNDA1MDY=",
"token": "64c420939814c62889ea143d17736841"
}
]}
however i am not able to Deserialize it to my Class that is structured like below
public class MyObject
{
public string usr_name { get; set; }
public string usr_fullname { get; set; }
public string usr_emailaddress { get; set; }
public string photo_url { get; set; }
public string token { get; set; }
}
i am using Newtonsoft JSON.Net for this purpose, this is my first time dealing with JSON inside C# so i am quite clueless no how or what to do. i've done several research only to find outdated tutorials or questions unlike my returned JSON value
so the php's response looks like this
and after trying to deserialize it, it looks like this

Your json string is not valid json - the wrapping {} are invalid. You should check how the json string is generated / encoded inside your php API.

If I had to guess, I'd say you serialized this object in PHP from a database query, which typically returns an array of rows. Which is why your JSON is an object with an array that contains an object.
There's an extra level of indirection in there so you need to remove that to deserialize. Try using array_pop in your PHP to to make sure you're only serializing a single object, or just use the fetch rather than fetchAll equivalent for your database interface in PHP if you only expect a single value. Otherwise, iterate over the array of objects after deserializing in C#.

That can be a soultion for that in PHP (if your json example is right):
$obj = new MyClass();//get empty instance
$arr = json_decode(trim($json,'}{'),true);//get array from json, but fix it first
//because {[{'key':'value'}]} is not valid!
$arr = $arr[0];//get sub array with real data
//bind all data to your object
array_walk($arr,function($v,$k) use ($obj){ $obj->{$k}=$v; });
print $obj->usr_name;// output: 12-34567
Why is {[{'key':'value'}]} not valid?
An Object Member MUST have a name!
So that would be valid json: {'content':[{'key':'value'}]}.
UPDATE: Forget this answer!! You want to do this in C# not in PHP :)

Related

Json Array cannot be deserialized

I would like to start by saying that I am not a developer and this is my very first time writing a code to this extend of complication (at least to me). Any help/guidance would be much appreciated.
The idea of this program is to retrieve the employee user ID (or signature) from an API URL once the name has been entered.
I have a JSON String
[{"signature":"JDOW","firstName":"Jane","fullName":"Dow, Jane","lastName":"Dow"}]
I am trying to deserialize it to a collection. But I am getting an error. Can somebody direct me to the right way to fix this?
namespace TimeSheet_Try11_Models
{
public class Employeename
{
[JsonProperty("Signature")]
public string Signature { get; set; }
[JsonProperty("FirstName")]
public string FirstName { get; set; }
[JsonProperty("FullName")]
public string FullName { get; set; }
[JsonProperty("LastName")]
public string LastName { get; set; }
}
}
I a trying to convert using the following code:
uri = StaticStrings.UrlIora + name;
var response = wc.DownloadString(uri);
Employeename status = JsonConvert.DeserializeObject<Employeename>(response);
The error I am getting is:
Newtonsoft.Json.JsonSerializationException: 'Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'TimeSheet_Try11_Models.Employeename' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly.
Deserialize the Json data for collection as:
var status = JsonConvert.DeserializeObject<List<Employeename>>(response);
or
List<Employeename> status = JsonConvert.DeserializeObject<List<Employeename>>(response);
Another thing is that, no need to use attribute [JsonProperty("anyProperty")] with your properties. Json can be deserialized without using it in attributes.
After getting the deserialzed data in status object, any value can be fetched from that object as:
string signature = status.Select(js => js.Signature).First();
Similarly other values can also be taken from the status.
Your JSON string has square brackets ([]) around it, which means it is a collection of items.
This is why the Deserialiser is erroring.
You need to either remove those brackets to give just one employee object in the input string, or tell DeserializeObject that it is a List you are deserialising.
var converted = JsonConvert.DeserializeObject<List<Employeename>>(response);
Working Fiddle here

Deserialising JSON String with JSON object serialised in the string

I am trying to deserialise a JSON string
string filter = #"[{""property"":""Student_PK"",""value"":""1""}]";
My first step was to
JsonConvert.DeserializeObject<Dictionary<string, string>>(filter)
which didn't work. However, I added a class to deserialise the object.
public class filterObject
{
[JsonProperty("property")]
string property {get; set;}
[JsonProperty("value")]
Object value { get; set; }
}
Running the following also did not work
JsonConvert.DeserializeObject<filterObject>(filter)
In this scenario, I do not have control over the filter string since this is generated by Sencha.
How else can I deserialise this JSON string as well as accommodating multiple JSON objects(property value combination) returned in a single string.
Data in the format of JSON array, So serialize Json with the List of the Object class, Try this one,
JsonConvert.DeserializeObject<List<filterObject>>(filter);
Your root is an array of Objects and not an object.
Try JsonConvert.DeserializeObject<Dictionary<string, string>[]>(filter)
Or with the second approach it should be JsonConvert.DeserializeObject<filterObject[]>(filter)

C# Parse/Deserialize JSON partially with Newtonsoft

I have to extract a part of json-string using .net or newtonsoft json.
JSON:
var json = "{\"method\":\"subtract\",\"parameters\":{\"minuend\":\"SOME_CUSTOM_JSON_OBJECT_DIFFERENT_FOR_EACH_METHOD\",\"subtrahend\":23}}";
C# Class:
class MyJson{
public string method { get; set; }
//public string parameters {get; set;}
public object parameters {get; set;}
}
I do not need to parse all the children of "parameters" json-object. "parameters" could be a very big object ([{obj1}...{obj1000}], objX of 1000 fields), parse which would be not performant.
I would like i.e. to pass it exactly as it is on some point, so conversion "string-C#object-string" would be redundant.
I do not want use Regexp or string transformations (string.Substring, Split and co), because of error margin, I know that all .net and newtonsoft string transformations based.
Question 1: if I define a property of type "object", how newtonsoft will handle this? (Documentation is worse than msdn, so I'm looking for the input from you, who already tried this).
static void Main(string[] args)
{
var json = "{\"method\":\"subtract\",\"parameters\":{\"minuend\":42,\"subtrahend\":23}}";
var data = JsonConvert.DeserializeObject<MyJson>(j);
// what internal representaion of data.parameters?
// How is it actually converted from json-string to an C# object (JObject/JsonObject).
}
In perfect case:
"parameters" is a string and calling
ExtractMyJson(jsonString)
gives me the json string of parameters.
Basically I need the newtonsoft version of
string ExtractMyJson(jsonString){
var p1 = jsonString.Split(",");
// .. varios string transformations
return pParams;
}
Note: please don't reference "dynamic" keyword or ask why no string transformations, it's the very specific question.
If you know that your parameters are unique you can do something like this:
class MyJson
{
public string method { get; set; }
public Dictionary<string,object> parameters { get; set; }
}
................
string json = "{\"method\":\"subtract\",\"parameters\":{\"minuend\":{\"img\": 3, \"real\": 4},\"subtrahend\":23}}";
var data = JsonConvert.DeserializeObject<MyJson>(json);
If you let it as object is going to receive the type Newtonsoft.Json.Linq.JObject.
Have you tried JTOKEN?
It is a rather simple solution to partially read basic or nested JSONs as described in this post.
For a nested JSON
{
"key1": {
"key11": "value11",
"key12": "value12"
}
"key2": "value2"
}
it would look like this
JToken token = JToken.Parse(json);
var value12 = token.SelectToken("key1.key12");
to get the element of the key "key12.
I think this could go nicely with your problem.
Well Objects are treated the same way your parent object is treated. It will start from the base of the graph. So if you have something like:
Person
{
Address Address {get;set;}
}
The Json will start Deserializing Address and then add in the Person object.
If you want to limit thesize of the graph depth you can use a setting like :
JsonConvert.DeserializeObject<List<IList<IList<string>>>>(json, new JsonSerializerSettings
{
MaxDepth = 2
});
For more configurations of the JsonSerializer check JsonSerializerSettings
If your field is an object then that object will have the KeyValuePair of every property that it holds, based on that when you cast that field you can access that type.(the behaviour is the same as assigning a type to an object in C#).
Update: So if you question using JsonObject or type, well JObject is and intermediary way to construct the json format in a generic format. But using the Type deserializatin means you can ignore properties you are not interested in. Mapping to a json with a type makes more sense because it creates a new object and dismisses the old JObject.

Json.net how to remove multiple node from json string after the json serialized twice?

There is a model here:
public class RoomInfo
{
public string Room { get; set; } // this is a json string
public bool Opened { get; set; }
}
After I JsonConver.Serialize(RoomInfo)
There is a new json string:
{"Room":
"{
"RoomId":6,
"RoomNo":"101",
"Price":20.0,
"IsPayByTime":1,
"AddTime":20150814135504
},
"Opened":true
"}
But the problem is I want to remove the RoomNo and AddTime
As you see the Room has been serialized twice
Every time I get the result I need to remove the node from Json string, and then save it to database, So I need a hight performance way to do it.
I try to use [JsonIgnore] before when it was a Model of Room, but sometimes I need these 2 field in my json string, but sometimes need to remove. So I can't use that attribute. that's why I just want to remove it after convert to json string.
Is there any way to remove it use a high performance way? thank you.
After you parse the string do the following:
jsonObj.Property("AddTime").Remove();

Json Stream in Wcf c# service to array

I'm really bad with C# and would like your help doing the following; I am currently passing a Json Array to my WCF webservice. I need to take the json array and insert it into a list. I have no idea to deserialize in C#. Please suggest to me what is the best way of achieving this. My code looks as follows:
public String UpdateOrderAddress(Stream userInfo)
{
try
{
StreamReader reader = new StreamReader(userInfo);
string JSONdata = reader.ReadToEnd();
if (JSONdata == null)
{
return "null";
}
return JSONdata; // Success !
}
catch (Exception e)
{
return e.ToString();
}
}
This is the data in the string that I get from the reader
[{"date":"2013-02-22 15:30:374:021","id":"1","description":"test","name":"test"},
"date":"2013-02-25 11:56:926:020","id":"2","description":"ghy","name":"fhh"},
"date":"2013-02-25 11:56:248:026","id":"3","description":"ghfm","name":"run"}]
The code you posted doesn't show how are you trying to deserialize your json string so I don't really follow what's the relevance here but in any case, this is how to deserialize JSON into a concrete C# class.
Create a class that matches the structure of your Javascript objects as so:
public class Data
{
public string Date {get;set;}
public int ID {get;set;}
public string Description {get;set;}
public string Name {get;set;}
}
Deserialize it using the JavascriptSerializer as so:
var deserializedData = new JavaScriptSerializer().Deserialize<List<Data>>(jsonString);
Note that your original JSON string is incorrectly formatted. It's missing the opening { on each element of the array. It should really be:
[{"date":"2013-02-22
15:30:374:021","id":"1","description":"test","name":"test"},
{"date":"2013-02-25
11:56:926:020","id":"2","description":"ghy","name":"fhh"},
{"date":"2013-02-25
11:56:248:026","id":"3","description":"ghfm","name":"run"}]
Now, if you attempt to deserialize the above, as so:
string json = #"[{""date"":""2013-02-22 15:30:374:021"",""id"":""1"",""description"":""test"",""name"":""test""},
{""date"":""2013-02-25 11:56:926:020"",""id"":""2"",""description"":""ghy"",""name"":""fhh""},
{""date"":""2013-02-25 11:56:248:026"",""id"":""3"",""description"":""ghfm"",""name"":""run""}]";
var deserializedData = new JavaScriptSerializer().Deserialize<List<Data>>(json);
You'll get a nice List<Data> back.
Also note that I didn't use a DateTime field for the corresponding date field in your Javascript object, the reason being that your sample dates are not valid DateTimes or at least a DateTime object cannot be created from that string representation. For instance, "15:30:374:021" makes no sense - I would imagine that 374 is the seconds field...
You need to add a reference to System.Web.Extensions to be able to use the JavascriptSerializer.
You can create a representative class with your required properties to hold the values and use the JavascriptSerializer class. Call the Deserialize<T> method specifying your type to deserialize the JSON into your code.
Links in class names for reference.
You can use Newtonsoft.Json Library. All you will need to do is:
List<YourClass> yourClassList = JsonConvert.DeserializeObject<List<YourClass>>(JSONdata);
You find more information, even samples here

Categories