How to Deserialize JSON array(or list) in C# - c#

public static string DeserializeNames()
{
// Json I am passing for the deserialization.
JsonStream= "{
"head": {
"Rows": [
"test 1",
[
[
{
"#Key": "Domain",
"#value": "LocalHost"
},
{
"#Key": "Cookie name(s)",
"#value": "Google"
},
{
"#Key": "Purpose",
"#value": "Test"
},
{
"#Key": "lifetime",
"#value": "test"
}
]
]
]
}
}"
//deserialize JSON from file
JavaScriptSerializer serializer = new JavaScriptSerializer();
var cookieList = serializer.Deserialize<List<Cookie>>(JsonStream).ToList();
}
//Class descriptions
//I have created below classes for the deserialization. Records are not deserialized i am getting zero record count.
public class Categorization
{
public string categorizationName { get; set; }
public List<object> KeyValue{ get; set; }
}
public class Head
{
public IList<Categorization> Rows { get; set; }
}
public class Cookie
{
public Head head { get; set; }
}
Also created below set of the classes and tried the deserialization, Still no luck
public class Head
{
public List<object> Rows { get; set; }
}
public class Cookie
{
public Head head { get; set; }
}
I am getting count as 0 i am not able to fetch any record.
Please help !!

I have modified the Json as below and stored in in the file "test.json" :
{
"head": {
"TestRows": [
[
{
"Key": "Domain",
"value": "Google"
},
{
"Key": "Cookie",
"value": "Test"
},
{
"Key": "Use for",
"value": "Test."
},
{
"Key": "Expire Time",
"value": "1 hour"
}
]
]
}
}
And created below set of classes :
public class Head
{
public IList<List<Dictionary<string, object>>> TestRows{ get; set; }
}
public class Cookie
{
public Head Head { get; set; }
}
var baseDirectory = AppDomain.CurrentDomain.BaseDirectory;
var path= Path.Combine(baseDirectory, "test.json");
//deserialize JSON from file
string JsonStream = System.IO.File.ReadAllText(path, Encoding.Default);
var DeserializedCookieList = JsonConvert.DeserializeObject<Cookie>(JsonStream);
Deserialization is working properly.

Related

Add item to JSON array section in C#

{
"name": "Not Okay Bears Solana #1",
"image": "ipfs://QmV7QPwmfc6iFXw2anb9oPZbkFR75zrtw6exd8LherHgvU/1.png",
"attributes": [
{
"trait_type": "Background",
"value": "Amethyst"
},
{
"trait_type": "Fur",
"value": "Warm Ivory"
},
{
"trait_type": "Mouth",
"value": "Clean Smile"
},
{
"trait_type": "Eyes",
"value": "Not Okay"
},
{
"trait_type": "Hat",
"value": "Bucket Hat"
},
{
"trait_type": "Clothes",
"value": "Plaid Jacket"
},
{
"trait_type": "Eyewear",
"value": "Plastic Glasses"
}
],
"description": "Not Okay Bears Solana is an NFT project for mental health awareness. 10k collection on the Polygon blockchain. We are not okay."
}
I need to add an object to attributes.
How to do this?
My JSON classes:
public class Attribute
{
public string trait_type { get; set; }
public string value { get; set; }
}
public class Root
{
public string name { get; set; }
public string image { get; set; }
public List<Attribute> attributes { get; set; }
public string description { get; set; }
}
try this, in this case you don't need any classes
var jsonObject = JObject.Parse(json);
JObject obj = new JObject();
obj.Add("trait_type", "type");
obj.Add("value", "value");
((JArray)jsonObject["attributes"]).Add(obj);
var newJson=jsonObject.ToString();
but if you need the data not a json , you can use this code
Root data = JsonConvert.DeserializeObject<Root>(json);
data.attributes.Add(new Attribute { trait_type="type", value="value"});

How do I create a List or Array of different data types from C# to be saved to JSON in Unity

I would like my output JSON to contain a simple array shown below
{
"attributes":[
{
"trait_type": "Background",
"value": "Green"
},
{
"trait_type": "Body",
"value": "Body_1"
},
{
"trait_type": "Outfit",
"value": "Beach_Singlet"
},
{
"display_type":"date",
"trait_type":"birthday",
"value":869270400
}
]
}
Notice how the last item is different from the previous items in the array. The variable named "value" is also an integer as compared to the previous entries as strings.
How do I go about in order to be able to output my JSON as shown above? I have tried creating a class that can store all the information, but I cannot reuse the name "value" for both an int and string declaration, and also do not wish to show the variables if their value is null
(Example shown below)
{
"attributes": [
{
"display_type": "",
"trait_type": "Background",
"value": "Green"
},
{
"display_type": "",
"trait_type": "Body",
"value": "Body_1"
},
{
"display_type": "",
"trait_type": "Outfit",
"value": "Beach_Singlet"
},
{
"display_type": "date",
"trait_type": "birthday",
"value": 869270400
}
]
}
You can use object type.
using Newtonsoft.Json;
var list = new AttributeList
{
attributes = new []{
new Attribute
{
trait_type = "Background",
value = "green"
},
new Attribute
{
display_type = "date",
trait_type = "birthday",
value = 869270400
}
}
};
var json = JsonConvert.SerializeObject(list, Formatting.Indented);
Console.WriteLine(json);
public class Attribute
{
public object value { get; set; }
public string trait_type { get; set; }
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public string display_type { get; set; }
}
public class AttributeList
{
public Attribute[] attributes { get; set; }
}
Output:
{
"attributes": [
{
"value": "green",
"trait_type": "Background"
},
{
"value": 869270400,
"trait_type": "birthday",
"display_type": "date"
}
]
}
try this
var attributes=new List<Attribute>{
new AttributeString{
trait_type="Background",
value="green"
},
new AttributeInt{
display_type ="date",
trait_type="birthday",
value=869270400
}
};
var jsonSerializerSettings = new JsonSerializerSettings()
{
TypeNameHandling = TypeNameHandling.Objects,
NullValueHandling=NullValueHandling.Ignore,
Formatting=Newtonsoft.Json.Formatting.Indented
};
var json = JsonConvert.SerializeObject(attributes,jsonSerializerSettings);
classes
public class Attribute
{
public string trait_type { get; set; }
public string display_type { get; set; }
}
public class AttributeString:Attribute
{
public string value { get; set; }
}
public class AttributeInt:Attribute
{
public int value { get; set; }
}
public class AttributeList
{
public List<Attribute> attributes { get; set; }
}

Deserializing JSON with numeric string keys in C#

{
Items: [
{
"title": "Object1",
"preview": {
"2048": "preview_9212.jpg",
"1024": "preview_6693.jpg",
}
},
{
"title": "Object2",
"preview": {
"2048": "preview_9888.jpg",
"1024": "preview_6890.jpg",
}
},
{
"title": "Object3",
"preview": {
"2048": "preview_9822.jpg",
"1024": "preview_6848.jpg",
}
}
]
}
I usually deserialise like this:
[Serializable]
public class JsonParser
{
public string title;
public List<Preview> preview;
}
[Serializable]
class Preview
{
public string 2048;
}
But since 2048 is an Integer is not possible to use this way.
I tried to deserialize the JSON to get preview like these:
public class Preview
{
[JsonProperty("2048")]
public string imageNumber { get; set; }
}
var user = JsonConvert.DeserializeObject<Preview>(jsonValue);
or
var json = JObject.Parse(jsonValue);
var preview = json["preview"].ToObject<Dictionary<string, string>>();
foreach (var entry in preview)
{
Debug.Log(entry.Key);
Debug.Log(entry.Value);
}
I got: NullReferenceException: Object reference not set to an instance of an object.
I also tried Deserializing JSON that has an int as a key in C# but again NullReferenceException;
Thanks for any help!
Since you have numeric string properties, you have 2 main choices:
Use something like [JsonProperty("2048")] and select valid name for the property
Or use a dictionary. This looks much more flexible for me, so you can try this code
Data data= JsonConvert.DeserializeObject<Data>(json);
string preview2048 = data.Items[0].Preview["2048"]; //preview_9212.jpg
or more complicated search using Linq
string obj3Preview2048 = data.Items.Where(i=> i.Title == "Object3")
.Select(i =>i.Preview["2048"]).FirstOrDefault(); //preview_9822.jpg
classes
public partial class Data
{
[JsonProperty("Items")]
public List<Item> Items { get; set; }
}
public partial class Item
{
[JsonProperty("title", NullValueHandling = NullValueHandling.Ignore)]
public string Title { get; set; }
[JsonProperty("token")]
public string Token { get; set; }
[JsonProperty("preview")]
public Dictionary<string, string> Preview { get; set; }
}
and you have some typos in json you posted, and I fix "type" to "title" in one of json objects. This is a fixed version
{
"Items": [{
"title": "Object1",
"token": "6561b1bbe5f1958848jhgd43d2",
"preview": {
"2048": "preview_9212.jpg",
"1024": "preview_6693.jpg"
}
},
{
"title": "Object2",
"token": "4a42eb54648DSFhUI664654d25",
"preview": {
"2048": "preview_9888.jpg",
"1024": "preview_6890.jpg"
}
},
{
"type": "Object3",
"token": "3fba64831dghkjgfkl5dfaegoj9",
"preview": {
"2048": "preview_9822.jpg",
"1024": "preview_6848.jpg"
}
}
]
}

How to select items from json response c#

I am try to create a wild card search feature.
I have a json response it contains the username. i have to search the user like te*, so it will display corresponding usernames.
LIke test1, test2
The below code i am using to get the response
var JSONResponse = await SendGraphRequest("/users/", null, null, HttpMethod.Get);
i have tried below code and trying to filter in graph only
i have try to filter in graph only
var JSON = await SendGraphRequest("/users/", $"$filter=startswith(givenname,'b')", null, HttpMethod.Get);
var graphUserResponse2 = JsonConvert.DeserializeObject<GraphUserResponseMapping>(JSON);
so instead of given name i want to try to filter using user name.
i am using newtonsoft to parse the json but it is difficult to get the username in list then then i will apply the wild card search. but the problem is how to get the username and store in a list?
The below is json response
{
"odata.metadata": "test",
"odata.nextLink":"test",
"value": [
{
"odata.type": "Microsoft.DirectoryServices.User",
"objectType": "User",
"signInNames": [
{
"type": "emailAddress",
"value": "test1#gmail"
},
{
"type": "username",
"value": "Test1"
}
],
"personId": "1"
},
{
"odata.type": "Microsoft.DirectoryServices.User",
"objectType": "User",
"signInNames": [
{
"type": "emailAddress",
"value": "test2#gmail.com"
},
{
"type": "username",
"value": "Test2"
}
],
"personId": "2"
}
]
}
TIA
Roger!
You can use a Class ex:
YourClassName.cs
code inside this class
public class SignInName
{
public string Type { get; set; }
public string Value { get; set; }
}
public class Value
{
[JsonProperty(PropertyName = "odata.type")]
public string OdataType { get; set; }
public string ObjectType { get; set; }
public List<SignInName> SignInNames { get; set; }
public string PersonId { get; set; }
}
public class YourClassName
{
[JsonProperty(PropertyName = "odata.metadata")]
public string OdataMetadata { get; set; }
[JsonProperty(PropertyName = "odata.nextLink")]
public string OdataNextLink { get; set; }
public List<Value> Value { get; set; }
}
So you can search for the usernames and put it into a list.
Ex:
List<string> userNameList = new List<string>();
var json = "{ \"odata.metadata\": \"test\", \"odata.nextLink\":\"test\", \"value\": [ { \"odata.type\": \"Microsoft.DirectoryServices.User\", \"objectType\": \"User\", \"signInNames\": [ { \"type\": \"emailAddress\", \"value\": \"test1#gmail\" }, { \"type\": \"username\", \"value\": \"Test1\" } ], \"personId\": \"1\" }, { \"odata.type\": \"Microsoft.DirectoryServices.User\", \"objectType\": \"User\", \"signInNames\": [ { \"type\": \"emailAddress\", \"value\": \"test2#gmail.com\" }, { \"type\": \"username\", \"value\": \"Test2\" } ], \"personId\": \"2\" } ] }";
var yourClassName = JsonConvert.DeserializeObject<YourClassName>(json);
foreach (var value in yourClassName.Value)
{
userNameList.AddRange(value.SignInNames.Where(x => x.Type == "username").Select(x => x.Value).ToList());
}

Getting Data from a JObject

I have stored JSON data in a string and by using the JObject, I am trying to get values from JSON data. I am just not able to figure out that what is the underlying issue with my code because I am not able to get data from the JSON object. A snippet of my code is attached below. If some can help me out to figure out the issue it will be immensely appreciated.
String text;
try {
var response = (HttpWebResponse)request.GetResponse();
using (var sr = new StreamReader(response.GetResponseStream()))
{
text = sr.ReadToEnd();
JObject jObject = JObject.Parse(text);
string haha = (string)jObject["value/segments/requests/count/sum"];
ViewBag.gotstring = haha;
}
System.Diagnostics.Debug.WriteLine(text);
} catch(Exception e) {
System.Diagnostics.Debug.WriteLine(url);
System.Diagnostics.Debug.WriteLine(e.ToString()); }
return View();
Here is the JSON:
{
"value": {
"start": "2018-08-12T04:44:38.941Z",
"end": "2018-08-12T16:44:38.941Z",
"interval": "PT30M",
"segments": [
{
"start": "2018-08-12T14:00:00Z",
"end": "2018-08-12T14:30:00Z",
"segments": [
{
"requests/count": {
"sum": 2
},
"request/name": "GET Home/Index"
},
{
"requests/count": {
"sum": 1
},
"request/name": "GET Home/About"
},
{
"requests/count": {
"sum": 1
},
"request/name": "GET Home/Contact"
}
]
},
{
"start": "2018-08-12T14:30:00Z",
"end": "2018-08-12T15:00:00Z",
"segments": [
{
"requests/count": {
"sum": 2
},
"request/name": "GET Account/Register"
},
{
"requests/count": {
"sum": 1
},
"request/name": "GET Account/Login"
}
]
},
{
"start": "2018-08-12T15:30:00Z",
"end": "2018-08-12T16:00:00Z",
"segments": [
{
"requests/count": {
"sum": 8
},
"request/name": "GET Home/Index"
},
{
"requests/count": {
"sum": 8
},
"request/name": "GET Home/About"
}
]
}
]
}
}
jObject does not work this way. It returns dictionary that you can query by key, but keys are single level. I.e. you'll be able to get some data like this:
var haha = jObject["value"]["segments"];
But beyond that it gets very complex. You'll be much better off defining a C# class that represents your JSON and serialise into that. A simple `Edit=>Paste Special => JSON as Class" in Visual Studio gives this:
public class Rootobject
{
public Value value { get; set; }
}
public class Value
{
public DateTime start { get; set; }
public DateTime end { get; set; }
public string interval { get; set; }
public Segment[] segments { get; set; }
}
public class Segment
{
public DateTime start { get; set; }
public DateTime end { get; set; }
public Segment1[] segments { get; set; }
}
public class Segment1
{
[JsonProperty("requests/count")]
public RequestsCount requestscount { get; set; }
[JsonProperty("request/name")]
public string requestname { get; set; }
}
public class RequestsCount
{
public int sum { get; set; }
}
and then deserialise like this:
var serialised = JsonConvert.DeserializeObject<Rootobject>(json);
var haha = serialised.value.segments.FirstOrDefault().segments.FirstOrDefault().requestscount.sum;
And here is a working sample: https://dotnetfiddle.net/CZgMNE
Can you try:
EDIT: seems like segments is an array, this will get you the sum for first segment only
string haha = (string)jObject["value"]["segments"][0]["segments"]["requests/count"]["sum"];

Categories

Resources