0

I want many of them but I don't how to make so many I can only make one just like this here:

[
  {
    "NAME1": "Max1"
  }
]

But I want to make this:

[
  {
    "NAME1": "Max1"
  },
  {
    "NAME2": "Max2"
  },
  {
    "NAME3": "Max3"
  },
  {
    "NAME4": "Max4"
  }
]

How do I do it Here is my code:

public void nxt_Click(object sender, EventArgs e)
{
    List<Voc> _data = new List<Voc>();
    _data.Add(new Voc()
    {
        NAME = textBox1.Text
    });

    string jger2 = JsonConvert.SerializeObject(_data.ToArray(), Formatting.Indented);

    File.WriteAllText(@"D:\Users\Oxygen\Desktop\ss.json", jger2);    
}

public class Voc
{
    public string NAME { get; set; }
}

has anybody any ideas?

mason
  • 31,774
  • 10
  • 77
  • 121
BlauFx
  • 1
  • 1
  • 1
  • 6
    You have 1 object in your resulting json array because your list only consists of 1 item (ie. you only added 1 item). I am not sure what is surprising about this. – Igor Oct 19 '18 at 15:39
  • 3
    When you make a JSON array, the key is usually the same `[{"Name":"Name1"},{"Name":"Name2"},{"Name":"Name3"}]` and I believe the serialize object tries to match the key to the object properties. – Daniel Gale Oct 19 '18 at 15:40
  • 1
    You could use a dictionary (`Dictionary`) with this approach: https://stackoverflow.com/a/5597628/361842 ... however, why do you want to have `Name1, Name2, ..., NameN`; that format is most likely going to cause you issues down the line vs simply having `"Name": ["Value1", "Value2", "...", "ValueN"]`. – JohnLBevan Oct 19 '18 at 15:49
  • Actually what's the wrong with code. Did you want to change attribute value??.. If so you should go Dictionary method – Ashiq Hassan Oct 19 '18 at 15:52
  • You also do not have to call `ToArray()` on your list, it will work the same without it – maccettura Oct 19 '18 at 15:53
  • check your '_data' object! It might be losing its value on clicks. That is assuming you are not asking us how to do a for loop to get "many of them." – Adam Oct 19 '18 at 15:57

2 Answers2

0

First of all, your Array is poorly formatted.

It should be:

{
  "NAMES": [
    {
      "NAME": "Max1"
    },
    {
      "NAME": "Max2"
    },
    {
      "NAME": "Max3"
    },
    {
      "NAME": "Max4"
    }
  ]
}

Run that through json2Csharp.com and it will generate the following:

public class NAME
{
    public string NAME { get; set; }
}

public class RootObject  //Rename this
{
    public List<NAME> NAMES { get; set; }
}

Which you should be able to serialize and deserialize using almost any C# JSON library.

Ghost4Man
  • 1,040
  • 1
  • 12
  • 19
Chris Cudmore
  • 29,793
  • 12
  • 57
  • 94
0

Below are a couple of ways to do this, demonstrated in this fiddle.

The first uses anonymous types, which are objects which don't have a real class, but are constructed by assigning values to properties. However, to use these you need to know the property names at compile time; so this will only work if you know exactly how many names you'll have in your array. e.g.

var data = new object[] {
    new {Name1 = textBox1.Text}
    ,new {Name2 = textBox2.Text}
    ,new {Name3 = textBox3.Text}
    ,new {Name4 = textBox4.Text}
};

Another approach is to use a dictionary, which can be populated with name value pairs at runtime, then you can convert these to JSON. E.g.

var textBoxes = new [] {textBox1, textBox2, textBox3, textBox4};
var dict = new Dictionary<string,string>();
for (var i = 0; i< textBoxes.Length; i++) 
{
    dict.Add(string.Format("Name{0}", i), textBoxes[i].Text );
}

However

I would strongly advise against these methods; or rather this approach. JSON is designed to be made up of key-value pairs. They keys should be known, whilst the values can change. That means that if you have 4 different values for a name instead of holding 4 different names, you hold those values against that name; e.g.

{"Name": ["Max1","Max2","Max3","Max4"]}

...with the number of the element being defined by the array's index.

The C# for that looks like this:

SomeClass data = GetValues();
//...
public class SomeClass 
{
    public IEnumerable<string> Name {get;private set;}
    //or: public string[] Name {get;private set;}
    //...
}

If you really need to store the different names, those should be stored as values against the name key; e.g.

[
    {"Name": "Name1", "Value": "Max1"}
    ,{"Name": "Name2", "Value": "Max2"}
    ,{"Name": "Name3", "Value": "Max3"}
    ,{"Name": "Name4", "Value": "Max4"}
]

The C# for that looks like this:

IEnumerable<SomeClass> data = GetValues();
//or: SomeClass[] data = GetValues();
//...

public class SomeClass 
{
    public string Name {get;private set;}
    public string Value {get;private set;}
    //...
}

 

Full Code

using System;
using System.Linq;
using System.Collections.Generic;
using Newtonsoft.Json;

public class Program
{
    public static void Main()
    {
        //setup our test data
        var textBox1 = new TextBox("Max1");
        var textBox2 = new TextBox("Max2");
        var textBox3 = new TextBox("Max3");
        var textBox4 = new TextBox("Max4");

        //demo using anonymous objects (NB: property names must be known at compile time)
        var data = new object[] {
            new {Name1 = textBox1.Text}
            ,new {Name2 = textBox2.Text}
            ,new {Name3 = textBox3.Text}
            ,new {Name4 = textBox4.Text}
        };
        Console.WriteLine( JsonConvert.SerializeObject(data, Formatting.Indented));

        //demo using a dictionary
        var textBoxes = new [] {textBox1, textBox2, textBox3, textBox4};
        var dict = new Dictionary<string,string>();
        for (var i = 0; i< textBoxes.Length; i++) 
        {
            dict.Add(string.Format("Name{0}", i+1), textBoxes[i].Text );
        }
        Console.WriteLine("[" + string.Join(",", dict.Select( e => string.Format("{{\"{0}\": \"{1}\"}}", e.Key.Replace("\"","\"\""), e.Value.Replace("\"","\"\"") ) )) + "]"); //based on https://stackoverflow.com/questions/5597349/how-do-i-convert-a-dictionary-to-a-json-string-in-c/5597628#5597628
    }
}

//dummy class   
public class TextBox 
{
    public TextBox(string text){Text = text;}
    public string Text{get;private set;}
}
Community
  • 1
  • 1
JohnLBevan
  • 22,735
  • 13
  • 96
  • 178