TXN_747
TXN_747

Reputation: 79

Get JObject based on Seq value inside the JObject

I have a flat file system ( with fixed length definitions for fields - I can't change this legacy system ) where the sequence order is important to write to the flat file to. I am trying to get a JObject based on the sequence value inside the JObject. I have the following JSON Object:

{
    APPOINTMENT_ID: {
        value: '',
        seqPos: 1,
        dbSize: 2,
        dbType: 'C',
        xpath: 'DataSet0'   
        },
    NAME: {
        value: '',
        seqPos: 2,
        dbSize: 30,
        dbType: 'C',
        xpath: 'DataSet1'
    },
    DATE: {
        value: '',
        seqPos: 3,
        dbSize: 10,
        dbType: 'M',
        xpath: 'DataSet2'
    }
}

Currently I'm looping through the index and the JSON for a match and then setting the JOBject.

JObject joOuter = null;
for (int i = 1; i <= joNode.Count; i++)
{
    foreach (var jT in joNode)
    {
        if (i == jT.Value["seqPos"].Value<int>())
        {
            joOuter = jT.Value.Value<JObject>();
            break;
        }
    }
    // Do Work on the JObect
    joOuter["value"] = "doProcess";
}

I'd like to do this in 1 loop instead of the current nested code, without changing the whole JSON and retooling the key to be the sequence position.

Upvotes: 0

Views: 161

Answers (1)

L.B
L.B

Reputation: 116168

I would copy those JObjects to a dictionary...

var jObj = JObject.Parse(jsonstr);
var dict = jObj.Properties().Select(x => x.Value)
               .ToDictionary(x => (int)x["seqPos"], x => x);

//loop or access the objects by their index
dict[2]["value"] = "somevalue";

//see, jObj is changed accordingly....
var debug = jObj.ToString(Newtonsoft.Json.Formatting.Indented);

Upvotes: 1

Related Questions