cudev
cudev

Reputation: 33

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

Upvotes: 3

Views: 2942

Answers (1)

Serge
Serge

Reputation: 43860

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

Upvotes: 3

Related Questions