I am trying to parse a json and populate these values into an object with DataContractJsonSerializer. Having no luck with this yet.
The json is -
{
"0": [
547,
541,
507,
548,
519,
0
],
"1": [
573,
504
]
}
I have tried the following code:
try
{
string json = #"""0"":[547,541,507,548,519,0],""1"":[573,504]";
using (var memStream = new MemoryStream(Encoding.UTF8.GetBytes(json)))
{
var seraializer = new DataContractSerializer(typeof(MyClass));
var jsonParsed = seraializer.ReadObject(memStream);
}
}
catch(Exception ex)
{
}
Always getting an exception that the data is invalid at the root. But online json validators say this is a valid json.
MyClass -
[DataContract]
public class MyClass
{
[DataMember]
public Dictionary<string, List<int>> values { get; set; }
}
Thanks Patrick for providing me a working solution with Newtonsoft. But just to learn , I want to see what am I doing wrong with DataContractJsonSerializer. The code below gives me no exception, but I am not getting any values after the parsing is complete.
string json = #"{""0"":[547,541,507,548,519,0],""1"":[573,504]}";
using (var memStream = new MemoryStream(Encoding.UTF8.GetBytes(json)))
{
var seraializer = new DataContractJsonSerializer(typeof(Dictionary<string, List<int>>));
var jsonParsed = seraializer.ReadObject(memStream);
}
You should use Dictionary<string, List<int>> as the type to deserialize to. You also need to use the right serializer (DataContractSerializer is for XML, DataContractJsonSerializer for JSON):
var seraializer = new DataContractJsonSerializer(typeof(Dictionary<string, List<int>>), new DataContractJsonSerializerSettings() { UseSimpleDictionaryFormat = true });
var jsonParsed = seraializer.ReadObject(memStream);
Or for JSON.NET:
var x = JsonConvert.DeserializeObject<Dictionary<string, List<int>>>(json);
Related
Currently i am using unity to post comments that get saved in a firebase RTDB.
here is the posting code:
Comment NewComment = new Comment("User1", "Great App!");
Dictionary<string, System.Object> childUpdates = new
Dictionary<string, System.Object>();
childUpdates["NewUpdate2"] = NewComment.ToDict();
_database.GetReference("DumbData").UpdateChildrenAsync(childUpdates);
which works well and posts the data to Firebase
For reference here is the Comment Class.
[System.Serializable]
public class Comment
{
public Comment(string Name,string Content)
{
this.Name = Name;
this.Content = Content;
}
public Dictionary<string,System.Object> ToDict()
{
Dictionary<string, System.Object> result = new Dictionary<string, System.Object>();
result["Name"] = this.Name;
result["Content"] = this.Content;
return result;
}
public string Name;
public string Content;
}
and the firebase registers the data received correctly.
but then when receiving the data, i would do
var dataSnapShot = await _database.GetReference("DumbData").GetValueAsync();
var Results = dataSnapShot.GetRawJsonValue();
var temp= JsonUtility.FromJson<Dictionary<string, Comment>>(Results)
but the thing is the FromJSON function returns Nulls everywhere , although the JSON is received correctly matching the structure on Firebase, for reference, the Results variable above looks like this:
{"NewUpdate":{"Content":"Great App!","Name":"User1"},"NewUpdate2":{"Content":"Great App!","Name":"User2"}}
so that's where i am stuck, i cannot deseriazlize the response back to be able to use it.
JsonUtility is very limited with nested objects, dictionaries, etc.
I'll recommend you to use another library for handling JSON serialize and deserialize, you can use Newtonsoft library for example, or use my own JsonManager (the repo includes and example of how it works and how to use it).
Newtonsoft:
Serialize:
Product product = new Product();
product.Name = "Apple";
product.Expiry = new DateTime(2008, 12, 28);
product.Sizes = new string[] { "Small" };
string json = JsonConvert.SerializeObject(product);
// {
// "Name": "Apple",
// "Expiry": "2008-12-28T00:00:00",
// "Sizes": [
// "Small"
// ]
// }
Deserialize:
string json = #"{
'Name': 'Bad Boys',
'ReleaseDate': '1995-4-7T00:00:00',
'Genres': [
'Action',
'Comedy'
]
}";
Movie m = JsonConvert.DeserializeObject<Movie>(json);
string name = m.Name;
// Bad Boys
So in your particular case that deserialize is not working, you should do something like:
Dictionary<string, Comment> temp = JsonConvert.DeserializeObject<Dictionary<string, Comment>>(json);
I have an anonymous JSON object and I need to add a list of strings (parameter: productOptions) to it. I need to put them into a keyless JSON-array. How would I do that with anonymous types?
public static List<Product> getProductsByProductOptions(long salespartnerGroupID, string marktCode, long producttypeGroupID, long productvalueGroupID, long deviceGroupID, List<string> productOptions)
{
RestRequest request = newRestRequest("getProductsByProductOptions");
var jsonObj = new
{
input = new
{
spbgid = salespartnerGroupID,
code = marktCode,
producttypegid = producttypeGroupID,
productvaluegid = productvalueGroupID,
devicegid = deviceGroupID,
productOptions = new { item = productOptions }
},
};
IRestResponse response = GetResponseAndSerialize(jsonObj, request);
BaseProduct myDeserializedClass = JsonConvert.DeserializeObject<BaseProduct>(response.Content);
return myDeserializedClass.#return.item;
}
I need the JSON to be like this:
"input": {
"spbgid": 3797,
"code": "xxx",
"producttypegid": 5239,
"productvaluegid": 0,
"devicegid": 4030,
"productOptions": {
"item": [
"SCREEN_PROTECTOR", "REPLACEMENT"
]
}
}
I am not sure why but using the RestSharp.JsonSerializer instead of JsonConvert fixed the problem. The anonymous object seemingly works just fine.
For some of my unit tests I want the ability to build up particular JSON values (record albums in this case) that can be used as input for the system under test.
I have the following code:
var jsonObject = new JObject();
jsonObject.Add("Date", DateTime.Now);
jsonObject.Add("Album", "Me Against The World");
jsonObject.Add("Year", 1995);
jsonObject.Add("Artist", "2Pac");
This works fine, but I have never really like the "magic string" syntax and would prefer something closer to the expando-property syntax in JavaScript like this:
jsonObject.Date = DateTime.Now;
jsonObject.Album = "Me Against The World";
jsonObject.Year = 1995;
jsonObject.Artist = "2Pac";
Well, how about:
dynamic jsonObject = new JObject();
jsonObject.Date = DateTime.Now;
jsonObject.Album = "Me Against the world";
jsonObject.Year = 1995;
jsonObject.Artist = "2Pac";
You can use the JObject.Parse operation and simply supply single quote delimited JSON text.
JObject o = JObject.Parse(#"{
'CPU': 'Intel',
'Drives': [
'DVD read/writer',
'500 gigabyte hard drive'
]
}");
This has the nice benefit of actually being JSON and so it reads as JSON.
Or you have test data that is dynamic you can use JObject.FromObject operation and supply a inline object.
JObject o = JObject.FromObject(new
{
channel = new
{
title = "James Newton-King",
link = "http://james.newtonking.com",
description = "James Newton-King's blog.",
item =
from p in posts
orderby p.Title
select new
{
title = p.Title,
description = p.Description,
link = p.Link,
category = p.Categories
}
}
});
Json.net documentation for serialization
Neither dynamic, nor JObject.FromObject solution works when you have JSON properties that are not valid C# variable names e.g. "#odata.etag". I prefer the indexer initializer syntax in my test cases:
JObject jsonObject = new JObject
{
["Date"] = DateTime.Now,
["Album"] = "Me Against The World",
["Year"] = 1995,
["Artist"] = "2Pac"
};
Having separate set of enclosing symbols for initializing JObject and for adding properties to it makes the index initializers more readable than classic object initializers, especially in case of compound JSON objects as below:
JObject jsonObject = new JObject
{
["Date"] = DateTime.Now,
["Album"] = "Me Against The World",
["Year"] = 1995,
["Artist"] = new JObject
{
["Name"] = "2Pac",
["Age"] = 28
}
};
With object initializer syntax, the above initialization would be:
JObject jsonObject = new JObject
{
{ "Date", DateTime.Now },
{ "Album", "Me Against The World" },
{ "Year", 1995 },
{ "Artist", new JObject
{
{ "Name", "2Pac" },
{ "Age", 28 }
}
}
};
There are some environment where you cannot use dynamic (e.g. Xamarin.iOS) or cases in where you just look for an alternative to the previous valid answers.
In these cases you can do:
using Newtonsoft.Json.Linq;
JObject jsonObject =
new JObject(
new JProperty("Date", DateTime.Now),
new JProperty("Album", "Me Against The World"),
new JProperty("Year", "James 2Pac-King's blog."),
new JProperty("Artist", "2Pac")
)
More documentation here:
http://www.newtonsoft.com/json/help/html/CreatingLINQtoJSON.htm
Sooner or later you will have property with a special character. e.g. Create-Date. The hyphen won't be allowed in property name. This will break your code. In such scenario, You can either use index or combination of index and property.
dynamic jsonObject = new JObject();
jsonObject["Create-Date"] = DateTime.Now; //<-Index use
jsonObject.Album = "Me Against the world"; //<- Property use
jsonObject["Create-Year"] = 1995; //<-Index use
jsonObject.Artist = "2Pac"; //<-Property use
Simple way of creating newtonsoft JObject from Properties.
This is a Sample User Properties
public class User
{
public string Name;
public string MobileNo;
public string Address;
}
and i want this property in newtonsoft JObject is:
JObject obj = JObject.FromObject(new User()
{
Name = "Manjunath",
MobileNo = "9876543210",
Address = "Mumbai, Maharashtra, India",
});
Output will be like this:
{"Name":"Manjunath","MobileNo":"9876543210","Address":"Mumbai, Maharashtra, India"}
You could use the nameof expression combined with a model for the structure you're trying to build.
Example:
record RecordAlbum(string Album, string Artist, int Year);
var jsonObject = new JObject
{
{ nameof(RecordAlbum.Album), "Me Against The World" },
{ nameof(RecordAlbum.Artist), "2Pac" },
{ nameof(RecordAlbum.Year), 1995 }
};
As an added benefit to removing the "magic string" aspect - this also will give you a little bit of refactor-ability. You can easily rename any given property name for the record and it should update the value returned by the nameof() expression.
You can use Newtonsoft library and use it as follows
using Newtonsoft.Json;
public class jb
{
public DateTime Date { set; get; }
public string Artist { set; get; }
public int Year { set; get; }
public string album { set; get; }
}
var jsonObject = new jb();
jsonObject.Date = DateTime.Now;
jsonObject.Album = "Me Against The World";
jsonObject.Year = 1995;
jsonObject.Artist = "2Pac";
System.Web.Script.Serialization.JavaScriptSerializer oSerializer =
new System.Web.Script.Serialization.JavaScriptSerializer();
string sJSON = oSerializer.Serialize(jsonObject );
I'm working with Json.Net to parse an array. What I'm trying to do is to pull the name/value pairs out of the array and assign them to specific variables while parsing the JObject.
Here's what I've got in the array:
[
{
"General": "At this time we do not have any frequent support requests."
},
{
"Support": "For support inquires, please see our support page."
}
]
And here's what I've got in the C#:
WebRequest objRequest = HttpWebRequest.Create(dest);
WebResponse objResponse = objRequest.GetResponse();
using (StreamReader reader = new StreamReader(objResponse.GetResponseStream()))
{
string json = reader.ReadToEnd();
JArray a = JArray.Parse(json);
//Here's where I'm stumped
}
I'm fairly new to JSON and Json.Net, so it might be a basic solution for someone else. I basically just need to assign the name/value pairs in a foreach loop so that I can output the data on the front-end. Has anyone done this before?
You can get at the data values like this:
string json = #"
[
{ ""General"" : ""At this time we do not have any frequent support requests."" },
{ ""Support"" : ""For support inquires, please see our support page."" }
]";
JArray a = JArray.Parse(json);
foreach (JObject o in a.Children<JObject>())
{
foreach (JProperty p in o.Properties())
{
string name = p.Name;
string value = (string)p.Value;
Console.WriteLine(name + " -- " + value);
}
}
Fiddle: https://dotnetfiddle.net/uox4Vt
Use Manatee.Json
https://github.com/gregsdennis/Manatee.Json/wiki/Usage
And you can convert the entire object to a string, filename.json is expected to be located in documents folder.
var text = File.ReadAllText("filename.json");
var json = JsonValue.Parse(text);
while (JsonValue.Null != null)
{
Console.WriteLine(json.ToString());
}
Console.ReadLine();
I know this is about Json.NET but times are a-changing so if anybody stumbles here while using .NET Core/5+ System.Text.Json please don't despair because
Try the new System.Text.Json APIs from .NET Blog show an example of this.
[
{
"date": "2013-01-07T00:00:00Z",
"temp": 23,
},
{
"date": "2013-01-08T00:00:00Z",
"temp": 28,
},
{
"date": "2013-01-14T00:00:00Z",
"temp": 8,
},
]
...
using (JsonDocument document = JsonDocument.Parse(json, options))
{
int sumOfAllTemperatures = 0;
int count = 0;
foreach (JsonElement element in document.RootElement.EnumerateArray())
{
DateTimeOffset date = element.GetProperty("date").GetDateTimeOffset();
(...)
This question already has answers here:
Deserialize JSON into C# dynamic object?
(31 answers)
Closed 8 years ago.
I have JSON which I need to deserialize, but I don't want to create class with property name.
here's what I get in JSON:
"[{"id":1,"width":100,"sortable":true}, {"id":"Change","width":100,"sortable":true}]"
So how could I do this?
Thanks for advance:)
You can use JavaScriptSerializer
var list = new JavaScriptSerializer()
.Deserialize<List<Dictionary<string, object>>>(json);
var id = list[0]["id"];
Or if you want, Json.Net
var list2 = JsonConvert.DeserializeObject<List<Dictionary<string, object>>>(json);
Json.Net also allows you to use dynamic
dynamic list = JsonConvert.DeserializeObject(json);
var wdth = list[0].width;
Using Json.net, you can deserialize directly to an anonymous class:
var json = "[{\"id\":1,\"width\":100,\"sortable\":true}, \"id\":\"Change\",\"width\":100,\"sortable\":true}]";
var myExempleObject = new {id = new object(), width = 0, sortable = false};
var myArray = JsonConvert.DeserializeAnonymousType(json, new[] {myExempleObject});
I'm assuming here id can be any object (as in your exemple it can be an int or a string), width must be an int and sortable must be a boolean.
You may use json.net
I am not sure if it is what you are looking for.
string json = #"{
'CPU': 'Intel',
'PSU': '500W',
'Drives': [
'DVD read/writer'
/*(broken)*/,
'500 gigabyte hard drive',
'200 gigabype hard drive'
]
}";
JsonTextReader reader = new JsonTextReader(new StringReader(json));
while (reader.Read())
{
if (reader.Value != null)
Console.WriteLine("Token: {0}, Value: {1}", reader.TokenType, reader.Value);
else
Console.WriteLine("Token: {0}", reader.TokenType);
}
using System;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
class Program
{
static void Main(string[] args)
{
string json = "[{\"id\":1,\"width\":100,\"sortable\":true}, {\"id\":\"Change\",\"width\":100,\"sortable\":true}]";
JArray array = JsonConvert.DeserializeObject(json) as JArray;
if (array != null)
{
foreach (JObject jObj in array)
Console.WriteLine("{0,10} | {1,10} | {2,10}", jObj["id"], jObj["width"], jObj["sortable"]);
}
Console.ReadKey(true);
}
}