pointers - Dynamically create struct of some type and unmarshal JSON into that instance

Pointers - Dynamically create struct of some type and unmarshal JSON into that instance

To dynamically create a struct of a specific type and unmarshal JSON into that instance in C, you can use a combination of malloc to allocate memory for the struct and libraries like jansson or cJSON to parse the JSON data. Here's a basic example using jansson:

First, make sure you have jansson library installed. If you're using a package manager like apt on Ubuntu, you can install it with:

sudo apt-get install libjansson-dev 

Here's an example code snippet demonstrating how to dynamically create a struct and unmarshal JSON into that instance using jansson:

#include <stdio.h> #include <stdlib.h> #include <jansson.h> // Define your struct typedef struct { int id; char name[50]; } MyStruct; int main() { // Allocate memory for the struct MyStruct *myStruct = (MyStruct *)malloc(sizeof(MyStruct)); if (myStruct == NULL) { fprintf(stderr, "Memory allocation failed\n"); return 1; } // Sample JSON data const char *json_data = "{\"id\": 1, \"name\": \"John\"}"; // Parse JSON json_error_t error; json_t *root = json_loads(json_data, 0, &error); if (!root) { fprintf(stderr, "JSON parsing error: %s\n", error.text); free(myStruct); return 1; } // Unmarshal JSON into the dynamically created struct json_t *id_json = json_object_get(root, "id"); json_t *name_json = json_object_get(root, "name"); if (id_json && name_json) { myStruct->id = json_integer_value(id_json); strncpy(myStruct->name, json_string_value(name_json), sizeof(myStruct->name)); printf("ID: %d, Name: %s\n", myStruct->id, myStruct->name); } else { fprintf(stderr, "Invalid JSON structure\n"); } // Free memory and clean up json_decref(root); free(myStruct); return 0; } 

In this example:

  • We define a struct MyStruct.
  • We allocate memory for an instance of MyStruct dynamically using malloc.
  • We parse the JSON data using json_loads from jansson.
  • We extract values from the parsed JSON and store them in the dynamically allocated struct.
  • Finally, we free the memory allocated for the struct and clean up.

Make sure to link your program against the jansson library when compiling. For example:

gcc -o program program.c -ljansson 

Replace MyStruct with your specific struct type, and adjust the JSON parsing and struct initialization logic accordingly based on your actual struct schema and JSON data format.

Examples

  1. "Golang dynamically create struct and unmarshal JSON"

    • Description: This query relates to dynamically creating a struct of a certain type in Golang and then unmarshalling JSON data into an instance of that struct.
    • Code Implementation:
      // Define struct type dynamically type DynamicStruct struct { // Define fields here Field1 string `json:"field1"` Field2 int `json:"field2"` } // Create an instance of the dynamic struct dynamicInstance := reflect.New(reflect.TypeOf(DynamicStruct{})).Elem().Interface() // Unmarshal JSON data into the dynamic struct instance jsonStr := `{"field1": "value1", "field2": 123}` err := json.Unmarshal([]byte(jsonStr), &dynamicInstance) 
  2. "Golang create struct instance from JSON dynamically"

    • Description: This query focuses on dynamically creating a struct instance in Golang from JSON data.
    • Code Implementation:
      // Define JSON data jsonStr := `{"field1": "value1", "field2": 123}` // Create an empty interface to hold the JSON data var dynamicInstance interface{} // Unmarshal JSON data into the empty interface err := json.Unmarshal([]byte(jsonStr), &dynamicInstance) 
  3. "Golang unmarshal JSON into dynamic struct"

    • Description: This query addresses unmarshalling JSON data into a dynamically created struct in Golang.
    • Code Implementation:
      // Define struct type dynamically type DynamicStruct struct { // Define fields here Field1 string `json:"field1"` Field2 int `json:"field2"` } // Create an instance of the dynamic struct dynamicInstance := DynamicStruct{} // Unmarshal JSON data into the dynamic struct instance jsonStr := `{"field1": "value1", "field2": 123}` err := json.Unmarshal([]byte(jsonStr), &dynamicInstance) 
  4. "Golang create struct from JSON with reflection"

    • Description: This query involves creating a struct in Golang from JSON data using reflection.
    • Code Implementation:
      // Define JSON data jsonStr := `{"field1": "value1", "field2": 123}` // Create a map to hold JSON key-value pairs var data map[string]interface{} // Unmarshal JSON data into the map err := json.Unmarshal([]byte(jsonStr), &data) // Iterate through map and create struct dynamically dynamicInstance := struct { Field1 string `json:"field1"` Field2 int `json:"field2"` }{ Field1: data["field1"].(string), Field2: int(data["field2"].(float64)), } 
  5. "Golang create struct from JSON with unknown keys"

    • Description: This query deals with creating a struct in Golang from JSON data where the keys are unknown beforehand.
    • Code Implementation:
      // Define JSON data jsonStr := `{"field1": "value1", "field2": 123}` // Create a map to hold JSON key-value pairs var data map[string]interface{} // Unmarshal JSON data into the map err := json.Unmarshal([]byte(jsonStr), &data) // Define struct type dynamically based on JSON keys type DynamicStruct struct { Field1 string Field2 int } // Create an instance of the dynamic struct dynamicInstance := DynamicStruct{ Field1: data["field1"].(string), Field2: int(data["field2"].(float64)), } 
  6. "Golang unmarshal JSON into dynamic struct with reflection"

    • Description: This query involves unmarshalling JSON data into a dynamically created struct in Golang using reflection.
    • Code Implementation:
      // Define JSON data jsonStr := `{"field1": "value1", "field2": 123}` // Create an empty interface to hold the JSON data var dynamicInstance interface{} // Unmarshal JSON data into the empty interface err := json.Unmarshal([]byte(jsonStr), &dynamicInstance) 
  7. "Golang dynamic struct creation and JSON unmarshalling"

    • Description: This query explores both dynamically creating a struct in Golang and then unmarshalling JSON data into an instance of that struct.
    • Code Implementation:
      // Define JSON data jsonStr := `{"field1": "value1", "field2": 123}` // Create a map to hold JSON key-value pairs var data map[string]interface{} // Unmarshal JSON data into the map err := json.Unmarshal([]byte(jsonStr), &data) // Define struct type dynamically based on JSON keys type DynamicStruct struct { Field1 string Field2 int } // Create an instance of the dynamic struct dynamicInstance := DynamicStruct{ Field1: data["field1"].(string), Field2: int(data["field2"].(float64)), } 
  8. "Golang dynamically create struct from JSON data"

    • Description: This query focuses on dynamically creating a struct in Golang from JSON data.
    • Code Implementation:
      // Define JSON data jsonStr := `{"field1": "value1", "field2": 123}` // Create a map to hold JSON key-value pairs var data map[string]interface{} // Unmarshal JSON data into the map err := json.Unmarshal([]byte(jsonStr), &data) // Define struct type dynamically based on JSON keys type DynamicStruct struct { Field1 string Field2 int } // Create an instance of the dynamic struct dynamicInstance := DynamicStruct{ Field1: data["field1"].(string), Field2: int(data["field2"].(float64)), } 
  9. "Golang dynamic struct creation and JSON unmarshalling using reflection"

    • Description: This query involves dynamically creating a struct in Golang and then unmarshalling JSON data into an instance of that struct using reflection.
    • Code Implementation:
      // Define JSON data jsonStr := `{"field1": "value1", "field2": 123}` // Create an empty interface to hold the JSON data var dynamicInstance interface{} // Unmarshal JSON data into the empty interface err := json.Unmarshal([]byte(jsonStr), &dynamicInstance) 

More Tags

matrix confusion-matrix artificial-intelligence libgdx lua ssl-certificate bit-manipulation associative-array formarray rss

More Programming Questions

More Investment Calculators

More Animal pregnancy Calculators

More Auto Calculators

More Weather Calculators