I need to deserialize JSON string - c#

string json = #" {""data"":[{""Name"":""Yaj"",""Number"":""null"",""Name"":""null"",""PhotoUrl"":""http://worldforme.com/rfr/fr"",""date"":""1994-06-14 00:00:00.000"",""ID"":""178"",""ssid"":""1"",""InOut"":""Incoming"",""Intime"":""null"",""OutTime"":""null"",""Por"":""null""}]}";
var dt = JsonConvert.DeserializeObject<mainlist>(json);
But dt returns null !
Please help

Your mainlist class needs to be structured to fit the key values of the json string.
Here's an example:
public class mainlist
{
public string Name {get; set;}
public int Number {get; set;}
[JsonProperty("PhotoUrl")] //Notice how this is different from the property name?
//This is because the property needs to fit exactly with the json string.
public string PhotoURL {get; set;}
//...
}
And if you still can't get it, well then there's something wrong with your json string.

Related

How can I parse JSON Array to string? [duplicate]

This question already has answers here:
How can I deserialize JSON with C#?
(19 answers)
Closed 2 years ago.
I'm trying to get JSON content with Newtonsoft.Json. To read one variable i have that method and It's working fine:
dynamic data = JObject.Parse(json);
return data.FirstName;
The problem begins if I want to read variable which is in array ex:
{"family": [{"fatherFirstName": "John", "motherFirstName": "July"}, {"fatherFirstName": "Jack", "motherFirstName": "Monika"]}
And for example I only want to get every father's first name.
Anybody know how can I do this?
Edit1:
Ok I fixed the convert from JArray to string but now there is problem that It reads family variable properly but If I want to get exact variable from Array it says that variable like this doesn't exist.
First of all, your JSON string has an invalid format. You can check it here to validate. Secondly, the best way to do this is to create a class and than use JsonConvert.DeserializeObject. On your case, here is the full working solution:
static void Main(string[] args)
{
string json = #"{'family': [{'fatherFirstName': 'John', 'motherFirstName': 'July'}, {'fatherFirstName': 'Jack', 'motherFirstName': 'Monika'}]}";
Families families = JsonConvert.DeserializeObject<Families>(json);
foreach (var family in families.family)
Console.WriteLine(family.fatherFirstName);
}
public class Families
{
public List<Family> family { get; set; }
}
public class Family
{
public string fatherFirstName { get; set; }
public string motherFirstName { get; set; }
}
public class familyData
{
public string fatherFirstName {get; set;}
public string motherFirstName {get; set;}
}
public class familyList
{
public List<familyData> family
}
and in your method
var data = JsonConvert.DeserializeObject<familyList>(json);

How to deserialize JSON with spaces in the attribute names?

I have a string array that I want to deserialize. Essentially, it is just a list of objects. Note that the attributes have spaces in the names:
[ { \"Event Name\": \"Hurricane Irma PR\", \"Storm Start (LST)\": \"2017-08-30\", \"Storm End (LST)\": \"2017-09-13\", \"Grid Cell Number\": 16412, \"Grid Cell State\": \"PR\", \"Grid Cell Name\": \"Grid26_0\", ...
I created a public class to template the string based on specific attributes that I want ( I don't want all the data) but I am not sure how to handle for the spaces in the names of the attributes that I want.
public class New_Events_Dataset
{
public string EventName { get; set; }
public string StormStart { get; set; }
public string StormEnd { get; set; }
public string GridCellState { get; set; }
public string GridCellName { get; set; }
public string USGSGageSiteNo { get; set; }
public string ReturnPeriodatGridCell { get; set; }
}
When I apply the deserializer with my class New_Events_Dataset like this:
var jsonResponse = returnJson.Deserialize<List<New_Events_Dataset>>(strresult);
string json = new JavaScriptSerializer().Serialize(jsonResponse);
return json;
I end up returning something like this. What am I doing wrong?
[{"EventName":null,"StormStart":null,"StormEnd":null,"GridCellState":null,"GridCellName":null,"USGSGageSiteNo":null,"ReturnPeriodatGridCell":null}
Unfortunately keys must match exactly each other.
One of the best ways to solve your problem is to define JsonProperty attribute for each property to get Deserialized object correctly. You can specify property's json key name with it.
You can take a look to this question and it's answer for better understanding:
An example of JsonProperty
Edit:
As in comments mentioned, because you are using JavaScriptSerializer JsonPropertyAttribute doesn't work in this situation.
But you can use it by adding Newtonsoft.Json Nuget Package and using it's deserilizer this way:
JsonConvert.DeserializeObject<AzureResourceData>(jsonString);

Deserialize JSON (Json.NET)

I need a little help with json deserialization. It's the first time I'm using Json, so I have just a little knowledge about it.
I get the following string using a webclient:
[{"name": "somename", "data": [[72, 1504601220], [null, 1504601280], ..., [125, 1504605840]]}]
and tried to serialize it with
JsonConvert.DeserializeObject<TestObject>(jsonstring)
My class looks like this:
public class TestObject
{
[JsonProperty(PropertyName = "name")]
public string TargetName { get; set; }
[JsonProperty(PropertyName = "data"]
public List<?????> DataPoints {get; set;}
}
How do I need to design my class to get the data values in some kind of collection so each entry contains the two values inside a bracket?
Thx for your patience and help!
Your data is a list of arrays containing nullable integers (by the looks of it)
[JsonProperty(PropertyName = "data"]
public List<int?[]> DataPoints {get; set;}
Try this website: http://json2csharp.com/
This website can save a lot of your time if you have just a plain JSON text. It helps you convert it to C# object, although you still have to double check it.
var data = "[{\"name\": \"somename\", \"data\": [[72, 1504601220], [null, 1504601280], [125, 1504605840]]}]";
var obj = JsonConvert.DeserializeObject<List<TestObject>>(data);
public class TestObject
{
[JsonProperty(PropertyName = "name")]
public string TargetName { get; set; }
[JsonProperty(PropertyName = "data")]
public List<int?[]> DataPoints { get; set; }
}
There is a some solution for this, C# 7.0 also supports ValueTuple such as this example.
List<(int? ,int?)> DataPoints { get; set; }
// if it not work try this.
List<List<int?>> DataPoints { get; set; }
If your json inner array elements count is equal to 2, so can assume to you use the value tuples.
Assume it is helpful for you.

Modify a JSON string

I have a string in JSON format as follows
string jsonStr = "{"Type":1, "Id":1000,"Date":null,"Group": "Admin","Country":"India","Type":1}";
I want to modify this string so that Id attribute should always be the first. The order of attributes matters.
Is there any way I can modify this string.
I tried searching google but did not find appropriate solution.
Any help would be appreciated.
EDIT:
I also tried to deserialize object using
object yourOjbect = new JavaScriptSerializer().DeserializeObject(jsonStr);
But here also the "type" attribute comes first. I dont find any way to move the attributes within this deserialized object
It's possible. Use the JsonProperty attribute, property Order.
http://www.newtonsoft.com/json/help/html/JsonPropertyOrder.htm.
Let me know if it works.
Instead of attempting to manipulate the order of the outputted JSON and comparing strings, I would transform both JSON strings that you want to compare, into objects and then perform your comparison. You could then compare individual properties or entire objects with something like the following:
void CompareJSON()
{
string json = #"{""Type"":1, ""Id"":1000,""Date"":null,""Group"": ""Admin"",""Country"":""India"",""Type"":1}";
string jsonToCompare = "JSON TO COMPARE";
MyObject myJsonObject = JsonConvert.DeserializeObject<MyObject>(json);
MyObject myJsonObjectToCompare = JsonConvert.DeserializeObject<MyObject>(jsonToCompare);
if (myJsonObject.Id == myJsonObjectToCompare.Id)
{
// Do something
}
}
class MyObject
{
public int Id { get; set; }
public int Type { get; set; }
public DateTime? Date { get; set; }
public string Group { get; set; }
public string Country { get; set; }
}
Please note that this example is carried out using the Newtonsoft.JSON library. More information on the library can be found here.
Just make your JSON into a c# class with Id first and then serialize it again if that is what you need. You do know that you have "Type" twice in the JSON string? In this solution it will get "fixed" so you only have it once as it should be. But if your string really is with two Type this wont work since the strings will be incorrect. If they really are like that you need to do some ugly string manipulation to fix the order but i hope the first string is incorrect only here and not in your code.
private void Test() {
string json = #"{""Type"":1, ""Id"":1000,""Date"":null,""Group"": ""Admin"",""Country"":""India"",""Type"":1}";
JavaScriptSerializer jsonSerializer = new JavaScriptSerializer();
MyJsonObject myJsonObject = jsonSerializer.Deserialize<MyJsonObject>(json);
string s = jsonSerializer.Serialize(myJsonObject);
//Returns: {"Id":1000,"Type":1,"Date":null,"Group":"Admin","Country":"India"}
}
class MyJsonObject {
public int Id { get; set; }
public int Type { get; set; }
public DateTime? Date { get; set; }
public string Group { get; set; }
public string Country { get; set; }
}

Is there a way to automatically initialize null child objects when serializing?

I'm using json.net to serialize my responses to the client
I'm building a controller action (in mvc) that produce a json string from types of objects
so it looks something like this:
string json = JsonConvert.SerializeObject(Activator.CreateInstance(type));
my problem is that when an object has an object inside of it (complex type), the activator assign null to it and then, the Json serializer doesn't serialize it at all
for example
if my object class looks like this:
public class Phone
{
public string Name {get; set;}
public Model Model {get; set;}
}
public class Model
{
public string Name {get; set;}
public string IMEI {get; set;}
}
the json string will be:
{"Name":null, "Model":null}
so is there a way to make be:
{"Name":null, "Model":{"Name":null, "IMEI":null}}
thank you all for your answers
OK
it took me some time to write this answer (stack overflow restriction) but i've found a great way to do it with reflection and recurssion I've created this method:
public void CreateFullInstance(object obj)
{
PropertyInfo[] properties = obj.GetType().GetProperties();
foreach(var property in properties)
{
Type propertyType = property.PropertyType;
if(!propertyType.IsPrimitive &&
propertyType.GetConstructor(Type.EmptyTypes) != null)
{
var val = Activator.CreateInstance(propertyType);
property.SetValue(obj,val);
CreateFullInstance(val);
}
}
}
when I call it, I just pass my initial:
var phone = Activator.CreateInstance(propertyType);
CreateFullInstance(phone);
var json = JsonConvert.SerializeObject(phone);
the downside for this method is that objects with no empty constructor will be ignored. I think I can fix that but then again as I said, these are POCO models so they all have empty constructors
You need to initialize Model in the constructor of Phone object.
public class Phone
{
public Phone()
{
Model = new Model();
}
public string Name {get; set;}
public Model Model {get; set;}
}
public class Model
{
public string Name {get; set;}
public string IMEI {get; set;}
}
You can also use the Activator.CreateInstance overload by which you can pass values as parameters to the constructor of a type.
Using Activator you are creating the object of main class that's why after serializing json string contain entries for properties of the class...{"Name":null, "Model":null}
Now if you want property names of Model class properties as well in the json string, then odo something because of which your inner class get initialized...
We can achieve it in two ways
1)In constructor of Phone class initialize Model class follows.
public class Phone
{
public Phone()
{
Model = new Model();
}
public string Name {get; set;}
public Model Model {get; set;}
}
2)
MyClassObject obj = (MyClassObject)Activator.CreateInstance(type);
obj.Model=new Model();
hope it helped

Categories

Resources