Json helper class in C++

Noah Aas 725 Reputation points
2025-03-15T07:59:48.3966667+00:00

Hello,

I need to send data from C++ to C#.

I would like to use the Marshal interface.

How can I serialise a data structure in C++?

What is the best way to deserialise it in C#?

Is there a json helper class in C++?

class MachineData
{
   public:
      int X;
      double Speed;
      CString MachineId;
      CStringArray ArrayData;
      CIntArray ArrayDataIndex;
   
C++
C++
A high-level, general-purpose programming language, created as an extension of the C programming language, that has object-oriented, generic, and functional features in addition to facilities for low-level memory manipulation.
3,892 questions
{count} votes

Accepted answer
  1. Minxin Yu 13,326 Reputation points Microsoft External Staff
    2025-03-17T02:47:22.76+00:00

    Hi,
    To use WinRT API, make sure templates is installed.
    The template projects have already configured the settings required for C++/WinRt.
    User's image

    For example:
    User's image

    #include"pch.h"
    #include <winrt/Windows.Foundation.h>
    #include <winrt/Windows.Data.Json.h>
    #include <winrt/Windows.Foundation.Collections.h>
    #include <iostream>
    
    using namespace winrt;
    
    using namespace Windows::Data::Json;
    
    int main () {
    
        init_apartment ();
    
        JsonObject obj;
        obj.Insert (L"message", JsonValue::CreateStringValue (L"Hello from C++/WinRT!"));
        obj.Insert (L"year", JsonValue::CreateNumberValue (2025)); //parameter: double input
    
        JsonArray arr;
    
        arr.Append (JsonValue::CreateStringValue (L"one"));
        arr.Append (JsonValue::CreateStringValue (L"two"));
        arr.Append (JsonValue::CreateStringValue (L"three"));
        obj.Insert (L"list", arr);
    
        hstring jsonStr = obj.Stringify (); //jsonStr = L"{\"message\":\"Hello from C++/WinRT!\",\"year\":2025,\"list\":[\"one\",\"two\",\"three\"]}"
    
        //string data
    
        std::wcout << L"Serialized JSON: " << jsonStr.c_str () << std::endl;
        std::string tempStr(jsonStr.begin (), jsonStr.end ());
        std::cout << "Serialized JSON: " << tempStr.c_str () << std::endl;
    
        return 0;
    
    }
    

    enter image description here

    Best regards,

    Minxin Yu


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.