Perhaps the JSON module from CCAN? http://ccodearchive.net/ It doesn't even depend on anything else from CCAN, and consists of exactly two files json.c and json.h

(The JSON module is here http://git.ozlabs.org/?p=ccan;a=tree;f=ccan/json )

Answer from Spudd86 on Stack Overflow
๐ŸŒ
GitHub
github.com โ€บ rpz80 โ€บ json
GitHub - rpz80/json: c json serialization library
Pure C json serialization library. For the complete API refer to the json.h.
Author ย  rpz80
Discussions

jemi: a compact JSON serializer for embedded systems
All the cool kids use CBOR and convert to JSON at bigger computers. More on reddit.com
๐ŸŒ r/embedded
28
85
August 27, 2022
C++ JSON Serialization - Stack Overflow
I want a way to serialize and deserialize Objects to JSON, as automatic as possible. Serialize: For me, the ideal way is that if I call in an instance JSONSerialize() it returns an string with a J... More on stackoverflow.com
๐ŸŒ stackoverflow.com
How do I turn a C# object into a JSON string in .NET? - Stack Overflow
Newtonsoft serializer is way faster and mor customizable then built in. Highly recommend to use it. Thanks for the answer @willsteel 2013-10-02T13:04:01.51Z+00:00 ... @JosefPfleger the pricing is for JSON.NET Schema, not JSON.NET the regular serializer, which is MIT 2015-06-03T19:51:01.283Z+00:00 More on stackoverflow.com
๐ŸŒ stackoverflow.com
Modern C++ JSON serialization library recommendations
The only feature you've asked for that nlohmann is to automate the to/from json for a type. This requires reflection which C++ doesn't have. Your best bet would be to combine reflection emulation from Hana with nlohmann, that's what I do and it works well. More on reddit.com
๐ŸŒ r/cpp
32
27
August 6, 2019
๐ŸŒ
sourcehut
sr.ht โ€บ ~rkta โ€บ microtojson
microtojson: A tiny JSON serializer in C
A simple embedded friendly JSON generator. No heap usage, no malloc(). As minimal stack usage as possible. Supports serialization to objects, arrays and primitives from int, unsigned int, _Bool and char arrays.
๐ŸŒ
Zltl
zltl.github.io โ€บ json-gen-c
json-gen-c: json-gen-c
โ€Fast, tiny, and friendly code generator that turns your C structs into fully featured JSON serializers/deserializers.
๐ŸŒ
Reddit
reddit.com โ€บ r/embedded โ€บ jemi: a compact json serializer for embedded systems
r/embedded on Reddit: jemi: a compact JSON serializer for embedded systems
August 27, 2022 -

Short form: I'm announcing (and welcoming comments for) jemi, a lightweight, pure-C JSON serializer.

Context: I needed to emit rather complex compound JSON data for a C-based project I'm working on. I could have done it all with sprintf(), but it got messy quickly. I looked at available libraries such as jansson and CCAN's json, but they both use malloc(), which isn't an option in my case.

So I created jemi ("Json EMItter"): you use jemi primitives to build up the JSON structure that you need, then call jemi_emit() to "walk the tree" and dump the resulting JSON string to the output of your choice.

Two files. No malloc. Unit tests included. MIT license. Comments welcome!

๐ŸŒ
GitHub
github.com โ€บ ibireme โ€บ yyjson
GitHub - ibireme/yyjson: The fastest JSON library in C ยท GitHub
a C++ and Python serialization library supporting TOON, JSON, and YAML with cross-format conversion.
Starred by 3.6K users
Forked by 305 users
Languages ย  C 97.7% | CMake 2.0%
๐ŸŒ
GitHub
github.com โ€บ kgabis โ€บ parson
GitHub - kgabis/parson: Lightweight JSON library written in C. ยท GitHub
In the following example I create a simple JSON value containing basic information about a person. void serialization_example(void) { JSON_Value *root_value = json_value_init_object(); JSON_Object *root_object = json_value_get_object(root_value); char *serialized_string = NULL; json_object_set_string(root_object, "name", "John Smith"); json_object_set_number(root_object, "age", 25); json_object_dotset_string(root_object, "address.city", "Cupertino"); json_object_dotset_value(root_object, "contact.emails", json_parse_string("[\"email@example.com\",\"email2@example.com\"]")); serialized_string = json_serialize_to_string_pretty(root_value); puts(serialized_string); json_free_serialized_string(serialized_string); json_value_free(root_value); }
Starred by 1.4K users
Forked by 337 users
Languages ย  C
Find elsewhere
๐ŸŒ
C# Corner
c-sharpcorner.com โ€บ article โ€บ serialization-2-json-serialization
Serialization (2) - JSON Serialization
July 17, 2024 - B - 3: Serializing and Deserializing JSON by Newtonsoft, Samples ... For simple scenarios where you want to convert to and from a JSON string, the SerializeObject() and DeserializeObject() methods on JsonConvert provide an easy-to-use wrapper over JsonSerializer.
๐ŸŒ
Newtonsoft
newtonsoft.com โ€บ json โ€บ help โ€บ html โ€บ serializewithjsonserializertofile.htm
Serialize JSON to a file
Movie movie = new Movie { Name = "Bad Boys", Year = 1995 }; // serialize JSON to a string and then write string to a file File.WriteAllText(@"c:\movie.json", JsonConvert.SerializeObject(movie)); // serialize JSON directly to a file using (StreamWriter file = File.CreateText(@"c:\movie.json")) { JsonSerializer serializer = new JsonSerializer(); serializer.Serialize(file, movie); }
Top answer
1 of 11
116

For C++20, just use a reflection library like boost-ext-reflect (not part of boost). C++ supports full reflection of aggregate types today.

For C++14, read the old answer.


There is no reflection in C++. True. But if the compiler can't provide you the metadata you need, you can provide it yourself.

Let's start by making a property struct:

template<typename Class, typename T>
struct PropertyImpl {
    constexpr PropertyImpl(T Class::*aMember, const char* aName) : member{aMember}, name{aName} {}

    using Type = T;

    T Class::*member;
    const char* name;
};

template<typename Class, typename T>
constexpr auto property(T Class::*member, const char* name) {
    return PropertyImpl<Class, T>{member, name};
}

Of course, you also can have a property that takes a setter and getter instead of a pointer to member, and maybe read only properties for calculated value you'd like to serialize. If you use C++17, you can extend it further to make a property that works with lambdas.

Ok, now we have the building block of our compile-time introspection system.

Now in your class Dog, add your metadata:

struct Dog {
    std::string barkType;
    std::string color;
    int weight = 0;
    
    bool operator==(const Dog& rhs) const {
        return std::tie(barkType, color, weight) == std::tie(rhs.barkType, rhs.color, rhs.weight);
    }
    
    constexpr static auto properties = std::make_tuple(
        property(&Dog::barkType, "barkType"),
        property(&Dog::color, "color"),
        property(&Dog::weight, "weight")
    );
};

We will need to iterate on that list. To iterate on a tuple, there are many ways, but my preferred one is this:

template <typename T, T... S, typename F>
constexpr void for_sequence(std::integer_sequence<T, S...>, F&& f) {
    using unpack_t = int[];
    (void)unpack_t{(static_cast<void>(f(std::integral_constant<T, S>{})), 0)..., 0};
}

If C++17 fold expressions are available in your compiler, then for_sequence can be simplified to:

template <typename T, T... S, typename F>
constexpr void for_sequence(std::integer_sequence<T, S...>, F&& f) {
    (static_cast<void>(f(std::integral_constant<T, S>{})), ...);
}

This will call a function for each constant in the integer sequence.

If this method don't work or gives trouble to your compiler, you can always use the array expansion trick.

Now that you have the desired metadata and tools, you can iterate through the properties to unserialize:

// unserialize function
template<typename T>
T fromJson(const Json::Value& data) {
    T object;

    // We first get the number of properties
    constexpr auto nbProperties = std::tuple_size<decltype(T::properties)>::value;
    
    // We iterate on the index sequence of size `nbProperties`
    for_sequence(std::make_index_sequence<nbProperties>{}, & {
        // get the property
        constexpr auto property = std::get<i>(T::properties);

        // get the type of the property
        using Type = typename decltype(property)::Type;

        // set the value to the member
        // you can also replace `asAny` by `fromJson` to recursively serialize
        object.*(property.member) = Json::asAny<Type>(data[property.name]);
    });

    return object;
}

And for serialize:

template<typename T>
Json::Value toJson(const T& object) {
    Json::Value data;

    // We first get the number of properties
    constexpr auto nbProperties = std::tuple_size<decltype(T::properties)>::value;
    
    // We iterate on the index sequence of size `nbProperties`
    for_sequence(std::make_index_sequence<nbProperties>{}, & {
        // get the property
        constexpr auto property = std::get<i>(T::properties);

        // set the value to the member
        data[property.name] = object.*(property.member);
    });

    return data;
}

If you want recursive serialization and unserialization, you can replace asAny by fromJson.

Now you can use your functions like this:

Dog dog;

dog.color = "green";
dog.barkType = "whaf";
dog.weight = 30;

Json::Value jsonDog = toJson(dog); // produces {"color":"green", "barkType":"whaf", "weight": 30}
auto dog2 = fromJson<Dog>(jsonDog);

std::cout << std::boolalpha << (dog == dog2) << std::endl; // pass the test, both dog are equal!

Done! No need for run-time reflection, just some C++14 goodness!

This code could benefit from some improvement, and could of course work with C++11 with some adjustments.

Note that one would need to write the asAny function. It's just a function that takes a Json::Value and call the right as... function, or another fromJson.

Here's a complete, working example made from the various code snippet of this answer. Feel free to use it.

As mentioned in the comments, this code won't work with msvc. Please refer to this question if you want a compatible code: Pointer to member: works in GCC but not in VS2015

2 of 11
15

For that you need reflection in C/C++, which doesn't exist. You need to have some meta data describing the structure of your classes (members, inherited base classes). For the moment C/C++ compilers don't automatically provide that information in built binaries.

I had the same idea in mind, and I used GCC XML project to get this information. It outputs XML data describing class structures. I have built a project and I'm explaining some key points in this page :

Serialization is easy, but we have to deal with complex data structure implementations (std::string, std::map for example) that play with allocated buffers. Deserialization is more complex and you need to rebuild your object with all its members, plus references to vtables ... a painful implementation.

For example you can serialize like this:

    // Random class initialization
    com::class1* aObject = new com::class1();

    for (int i=0; i<10; i++){
            aObject->setData(i,i);
    }      

    aObject->pdata = new char[7];
    for (int i=0; i<7; i++){
            aObject->pdata[i] = 7-i;
    }
    // dictionary initialization
    cjson::dictionary aDict("./data/dictionary.xml");

    // json transformation
    std::string aJson = aDict.toJson<com::class1>(aObject);

    // print encoded class
    cout << aJson << std::endl ;

To deserialize data it works like this:

    // decode the object
    com::class1* aDecodedObject = aDict.fromJson<com::class1>(aJson);

    // modify data
    aDecodedObject->setData(4,22);

    // json transformation
    aJson = aDict.toJson<com::class1>(aDecodedObject);
   
    // print encoded class
    cout << aJson << std::endl ;

Ouptuts:

>:~/cjson$ ./main
{"_index":54,"_inner":  {"_ident":"test","pi":3.141593},"_name":"first","com::class0::_type":"type","com::class0::data":[0,1,2,3,4,5,6,7,8,9],"com::classb::_ref":"ref","com::classm1::_type":"typem1","com::classm1::pdata":[7,6,5,4,3,2,1]}
{"_index":54,"_inner":{"_ident":"test","pi":3.141593},"_name":"first","com::class0::_type":"type","com::class0::data":[0,1,2,3,22,5,6,7,8,9],"com::classb::_ref":"ref","com::classm1::_type":"typem1","com::classm1::pdata":[7,6,5,4,3,2,1]}
>:~/cjson$ 

Usually these implementations are compiler dependent (ABI Specification for example), and require external descriptions to work (GCCXML output), thus are not really easy to integrate to projects.

๐ŸŒ
Quora
quora.com โ€บ How-do-you-deserialize-JSON-in-the-C-language-on-Windows
How to deserialize JSON in the C language on Windows - Quora
Answer: You can use the cJSON library or any of a large number of alternatives listed in the C section of JSON.org. cJSON is written to the c89 standard so it will happily compile in GCC, Visual Studio, MinGW and probably every common C compiler.
๐ŸŒ
Newtonsoft
newtonsoft.com โ€บ json โ€บ help โ€บ html โ€บ serializingjson.htm
Serializing and Deserializing JSON
SerializeObject and DeserializeObject both have overloads that take a JsonSerializerSettings object. JsonSerializerSettings lets you use many of the JsonSerializer settings listed below while still using the simple serialization methods. ... For more control over how an object is serialized, the JsonSerializer can be used directly.
๐ŸŒ
ByteHide
bytehide.com โ€บ home โ€บ jsonserialization in c#: step-by-step guide
JsonSerialization in C#: Step-by-Step Guide (2026)
December 25, 2023 - Ever wondered how to transmit your ... โ€“ an impressively handcrafted tool for this task. It helps you change or โ€œserializeโ€ your C# objects into JSON strings....
๐ŸŒ
Educative
educative.io โ€บ answers โ€บ how-to-serialize-an-object-using-the-jsonserializer-in-c-sharp
How to serialize an object using the JsonSerializer in C#
The JsonSerializer is a static class in the System.Text.Json namespace. It provides functionality for serializing objects to a JSON string and deserializing from a JSON string to objects.
๐ŸŒ
Microsoft Learn
learn.microsoft.com โ€บ en-us โ€บ dotnet โ€บ standard โ€บ serialization โ€บ system-text-json โ€บ how-to
How to serialize JSON in C# - .NET | Microsoft Learn
By default, all public properties are serialized. You can specify properties to ignore. You can also include private members. The default encoder escapes non-ASCII characters, HTML-sensitive characters within the ASCII-range, and characters that must be escaped according to the RFC 8259 JSON spec.
๐ŸŒ
Reddit
reddit.com โ€บ r/cpp โ€บ modern c++ json serialization library recommendations
r/cpp on Reddit: Modern C++ JSON serialization library recommendations
August 6, 2019 -

I'm currently using nlohmann/json but am wondering about better alternatives. In particular I'm wondering if there's anything that leverages C++11 or newer features that offers a more Go-like experience where you can conveniently serialize and deserialize structs without having to write a bunch of JSON<->struct CRUD code to copy values back and forth.

Is there anything like this? I've searched GitHub and haven't found anything better than what I'm using.

๐ŸŒ
Zserge
zserge.com โ€บ jsmn
The most simple JSON parser in C for small systems
Library sources are available at https://github.com/zserge/jsmn. Usually JSON parsers convert JSON string to internal object representation. But if you are using C it becomes tricky as there is no hash tables, no reflection etc.
๐ŸŒ
Medium
madhawapolkotuwa.medium.com โ€บ mastering-json-serialization-in-c-with-system-text-json-01f4cec0440d
Mastering JSON Serialization in C# with System.Text.Json | by Madhawa Polkotuwa | Medium
September 30, 2024 - I will cover how to serialize and deserialize objects, handle special cases like null values, format dates, and customize the output using JsonSerializerOptions.
๐ŸŒ
RealTimeLogic
realtimelogic.com โ€บ products โ€บ json
JSON C Source Code Library for IoT Communication
Our open source C JSON library simplifies converting C to JSON and JSON to C. The JSON library includes easy-to-use APIs for both serializing and deserializing C structures.