I have a C# class like the following:
public class FunctionCall
{
public string x {get; set;}
public int y {get; set;};
public object obj1 {get; set;};
public object obj2 {get; set;};
...
...
public object objN {get; set;};
}
with N >= 0. That means that there could be 0 or N > 0 objects objX So the problem is that I do not know at build time how many objects there will be and I need to serialize a complex structure that contains instances of the class.
The class FunctionCall is used to call OpenAI Assistant API passing the parameters of a function. ChatGPT expects the parameters to be embedded as JSon objects like the following. The Json is just a fragment that represents an objX instance embedded in a more complex document which has no dynamic fields so it's known at compile time and it's not a problem.
{
"type": "function",
"function": {
"name": "get_weather",
"description": "Determine weather in my location",
"parameters": {
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "The city and state e.g. San Francisco, CA"
},
"unit": {
"type": "string",
"enum": [
"c",
"f"
]
}
},
"required": [
"location"
]
}
}
}
"paramters" contains 2 objects: "location" and "unit", that are the 2 parameters of the function. Actually the JSon is a schema of the function's parameters. It should be serialized/deserialized using an instance of FunctionCall but the parameter objects are variable (depends on the functions that are specified during configuration at runtime, not at compile time) and cannot be passed as a collection, but as independent objects, like "location" and "unit".
For serialization/deserialization I use:
System.Text.Json.JsonSerializer.Serialize
System.Text.Json.JsonSerializer.Deserialize
And I tried to define a custom serializer but it doesn't seem to solve my problem.
I also tried to use Newtonsoft dynamic serialization (using a dynamic object), but it returns a JObject instead of an anonymous class instance with the fields I need, so it doesn't work for me.
Any helpful hint would be much appreciated.
I'm afraid you want to have a similar feature like what we can do in JS to read json content directly without having a model binding to the json data. If so, then I had a test with code below which might meet your requirement.
In addition, I don't think it's a good idea to handle data like this. It's not good for maintance at least... It's better for us to parse data format at first then create a model for it.