1

This is a somewhat unique problem I think... I can solve it easily in js/ts but am kinda stuck trying to implement this in the c# solution if at all possible.

Keeping it simple, so as not to write a novel here, I'm trying to improve some crappy json serialization. It's using dictionaries within dictionaries currently and it's assy to parse in JS. I wrote a TS library that "unpacks" the data into a more palatable format, but I'd love to move that server-side. The model is an xml object with elements unkown to the application (because it's defined in a CMS and can be modified any time even while the app is running) and because Vendor, I'm stuck with c#.

Super easy in JS - c#'s strong typing is killing me here.

How would you create this addKvp function in c# (where element would be of type object, i assume)

function addKvp (element, key, value) { element[key] = value; }

var abc = {};
addKvp(abc, "foo", "bar");
console.log(abc.foo);

where "key" is not a member of element.... yet.

The other directions I could tackle this from is maybe by manipulating the json serialization somehow or putting my typescript library that does exactly this in a node express server and have it sit between the two - but this'd be the "simplest" solve, if it is possible. It feels very against the c# grain.

3
  • Are you using Newtonsoft.Json or System.Text.Json for manipulating JSON? Commented Nov 10, 2021 at 18:02
  • Newtonsoft currently - I have control tho and it's the only thing this project does, so I can implement whatever Commented Nov 10, 2021 at 18:13
  • 1
    You could use JObject for abc and add value using JToken.FromObject() , i.e. element[key] = JToken.FromObject(value);. Or you could use ExpandoObject for abc, i.e. dynamic abc = new ExpandoObject(). Commented Nov 10, 2021 at 19:06

1 Answer 1

1

Got it!

If you have this problem and are using NewtonSoft, there's an object in Newtonsoft.Json.Linq called "JObject" which behaves almost exactly like I was wanting.

For simple explanation, my sample js function would be written as...

void AddKvp(JObject element, string key, (whatever type) value)
{
 element[key] = value;
 //doesn't seem to be able to convert <T> values on its own and this is just a sample so i'm not gonna bother figuring it out
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.