larasqp
September 3, 2024, 1:01am
1
I have found this snippet to convert a JSON
string to a class object:
#description.md
You can find usages in the [GDScript Unirest plugin](https://github.com/fenix-hub/unirest-gdscript)
This is a fast serializer/deserializer written in GDScript to convert a JSON (Dictionary) to a class, using something similar to the Reflection concecpt.
`json_to_class` can be used to convert a Dictionary to a Class. All keys in the Dictionary will be treated as variables and their types will be guessed in the best way possible.
A class (defined by the `class_name` keyword) must extend `Reference` or `Object` or be an inner `class`, or else Godot will not able to see its properties.
It is also possible to deserialize a JSON key to a class property with a different name using the `export` hint as a variable name.
example usage:
```gdscript
This file has been truncated. show original
json_class_converter.gd
static func json_string_to_class(json_string: String, _class: Object) -> Object:
var parse_result: JSONParseResult = JSON.parse(json_string)
if !parse_result.error:
return json_to_class(parse_result.result, _class)
return _class
static func json_to_class(json: Dictionary, _class: Object) -> Object:
var properties: Array = _class.get_property_list()
for key in json.keys():
for property in properties:
This file has been truncated. show original
Does anyone know of or have code that converts a dictionary/array to a class object?
Thank you all.
larasqp
September 3, 2024, 2:57am
2
Here is a very naive implementation based on the code above by Nicolò Santilio (without recursion or “frills” I do not understand like property["type"] == 17
):
func DictionaryToClass( dict : Dictionary, object : Object ) -> Object:
var properties : Array = object.get_property_list()
for key in dict.keys():
for property in properties:
if property.name == key:
object.set( key, dict[ key ] )
break
return object
1 Like