Add item to JSON array section in C# - 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"});

Related

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; }
}

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());
}

How to Deserialize JSON array(or list) in 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.

Json formatting with Json.net in C#

I am trying to parse a bunch of XML files into a single JSON file, which is already working.
The final JSON file looks like the following:
{
"items": [
{
"subItems": [
{
"Name": "Name",
"Value": "Value",
"Type": "text"
},
{
"Name": "Name",
"Value": "Value",
"Type": "text"
}
]
},
{
"subItems": [
{
"Name": "Name",
"Value": "Value",
"Type": "text"
},
{
"Name": "Name",
"Value": "Value",
"Type": "text"
},
...
Instead, I want to achieve the following structure:
{
"items": [
[
{
"Name": "Name",
"Value": "Value",
"Type": "text"
},
{
"Name": "Name",
"Value": "Value",
"Type": "text"
}
],
[
{
"Name": "Name",
"Value": "Value",
"Type": "text"
},
{
"Name": "Name",
"Value": "Value",
"Type": "text"
}
]
]
}
But I don't know how to define my objects in order to do so, my current structure is as follows:
public class Items
{
public List<Item> items;
}
public class Item
{
public List<SubItem> subItems;
}
public class SubItem
{
public string Name { get; set; }
public string Value { get; set; }
public string Type { get; set; }
}
How should I do this?
The answer is simple: turn your objects into lists: This will remove the prop names (and object notation in json).
public class Items
{
public List<Item> items; //list with prop name 'items'
}
public class Item : List<SubItem> // list in list like json notation
{
}
public class SubItem // Object in the list in list
{
public string Name { get; set; }
public string Value { get; set; }
public string Type { get; set; }
}
As #FlilipCordas noted Inheriting from list is bad practice (for good reason)
you are better of this way:
public class Items
{
public List<List<SubItem>> items; //list with list with prop name 'items'
}
public class SubItem // Object in the list in list
{
public string Name { get; set; }
public string Value { get; set; }
public string Type { get; set; }
}
Copy your json then go in Visual Studio.
Click on "Edit" > "Paste Special" > "Paste JSON as Classes"
All the classes are automatically created. I hope this tip could help you.

JSON Error converting value to type

It gives me error when deserializing this JSON File
{
"checkOut": "10:30",
"stars": 4,
"locationId": 953,
"propertyType": 6,
"checkIn": "15:00",
"trustyou": {
"languageSplit": [
{
"tripTypeSplit": [
{
"type": "family",
"percentage": 85
},
{
"type": "couple",
"percentage": 15
}
],
"name": "de",
"percentage": 100
}
],
"location": [
],
"reviewsCount": 83,
"popularity": 0,
"tripTypeSplit": [
{
"type": "family",
"percentage": 86
},
{
"type": "couple",
"percentage": 14
}
],
"sentimentScoreList": [
{
"categoryId": "14",
"ratio": "Good",
"shortText": "Great location",
"name": "Location",
"subcategories": [
],
"highlights": [
{
"text": "Beautiful location",
"confidence": 100
}
],
"reviewCount": 14,
"score": 100
},
{
"categoryId": "111",
"ratio": "Good",
"shortText": "Rather comfortable",
"name": "Comfort",
"subcategories": [
],
"highlights": [
],
"reviewCount": 5,
"score": 100
},
I have the following classes for this JSON
public class Root
{
[JsonProperty("checkIn")]
public string CheckIn { get; set; }
[JsonProperty("distance")]
public double Distance { get; set; }
[JsonProperty("hidden")]
public bool Hidden { get; set; }
[JsonProperty("trustyou")]
public Trustyou Trustyou { get; set; }
[JsonProperty("amenitiesV2")]
public AmenitiesV2 AmenitiesV2 { get; set; }
[JsonProperty("hasAirbnb")]
public bool HasAirbnb { get; set; }
[JsonProperty("checkOut")]
public string CheckOut { get; set; }
[JsonProperty("popularity")]
public int Popularity { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("id")]
public int Id { get; set; }
[JsonProperty("cntRooms")]
public int CntRooms { get; set; }
What seems to be the problem? i'm deserializing this using
string resp2 = await client.GetStringAsync("");
var hotelDetails = JsonConvert.DeserializeObject<IDictionary<string, HotelsDescriptionAPI.Root>>(resp2, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });
foreach (var hoteldesc in hotelDetails)
{
MessageBox.Show(hoteldesc.Value.Id);
}
and the exact error is
"Error converting value 24545 to type and Error converting value "10:30" to type 'HotelsDescriptionAPI.Root'. Path 'checkOut', line 1, position 19."
Im trying to get the value of "Id", What could be the problem with my code?
Your deserialization code should be:
var hotelDetails = JsonConvert.DeserializeObject<HotelsDescriptionAPI.Root>(resp2,
new JsonSerializerSettings {
NullValueHandling = NullValueHandling.Ignore
});
You're trying to deserialize it into a dictionary of string,Root, when the object itself is simply Root.
It does not seem to apply to your scenario, but note that when you do have JSON that is an array (root level children are array items, not properties), you may have to change the root object to subclass a compatible type.
For example:
public class RootObject : List<ChildObject>
{
}
public class ChildObject
{
public string Property1 { get; set; }
public string Property2 { get; set; }
}
For people that this does not help, and that are not using Entity Framework and or writing the domain classes by hand - make sure all your class properties match what is coming out of your data source in the same exact field order.

Categories

Resources