roybalderama
roybalderama

Reputation: 1640

Split String with Custom conditions and delimeters

What's the best way to split these string to a List<customObject>?

[
    [
        "a",
        "123",
        "456"
    ],
    [
        "b",
        "456",
        "789"
    ]
]

Say, I want to get the List of SampleObject with definition:

class SampleObject
{
    public string Letter { get; set; }
    public string FirstNumber { get; set; }
    public string SecondNumber{ get; set; }
}

Upvotes: 1

Views: 289

Answers (2)

competent_tech
competent_tech

Reputation: 44971

We use Json.Net's Jarray.Parse method for this. This is the example from their web help:

string json = @"[
  'Small',
  'Medium',
  'Large'
]";

JArray a = JArray.Parse(json);

You can create instances of your objects and then load from each element in the array.

Here is a working example that uses your sample string and class:

JArray aAllValues = JArray.Parse(json);
var SampleObjectCollection = new List<SampleObject>();

foreach (JArray aValues in aAllValues)
{
    var oSampleObject = new SampleObject();
    int index = 0;

    foreach (var oProperty in aValues.Children())
    {
        switch (index)
        {
            case 0:
                oSampleObject.Letter = oProperty.Value<String>();
                break;
            case 1:
                oSampleObject.FirstNumber = oProperty.Value<String>();
                break;
            case 2:
                oSampleObject.SecondNumber = oProperty.Value<String>();
                break;
        }

        index++;
    }

    SampleObjectCollection.Add(oSampleObject);
}

Upvotes: 2

Esteban Elverdin
Esteban Elverdin

Reputation: 3582

You can deserialize it using Json.Net into a dynamic object and then fill your custom objects

dynamic items = JsonConvert.DeserializeObject(jsonString);
var list = new List<SampleObject>();

foreach (var item in items)
{ 
    var sampleObject = new SampleObject
                           {
                               Letter = item[0].ToString(),
                               FirstNumber = item[1].ToString(),
                               SecondNumber = item[2].ToString()
                           }
    list.Add(sampleObject);        
}

Upvotes: 3

Related Questions