C
C#

help

❔ Convert JSON string to struct

Eentasy1/31/2023
I have a string in JSON format. How can I convert it to a struct?
c++
public struct config
{
public string ip { get; set; }
public int port { get; set; }
}

string _data = @"{""ip"":""127.0.0.1"",""port"":12345""}"; // I want to convert it to a config struct.
c++
public struct config
{
public string ip { get; set; }
public int port { get; set; }
}

string _data = @"{""ip"":""127.0.0.1"",""port"":12345""}"; // I want to convert it to a config struct.
TThinker1/31/2023
You can use System.Text.Json to do the deserialization, but I'm not sure it works with structs
TThinker1/31/2023
How to serialize and deserialize JSON using C# - .NET
Learn how to use the System.Text.Json namespace to serialize to and deserialize from JSON in .NET. Includes sample code.
Eentasy1/31/2023
It worked, thank you. @🌈 Thinker 🌈 For anyone who needs:
c++

public struct Configdata
{
public string ip { get; set; }
public string port { get; set; }
}

string _data = @"{""ip"":""127.0.0.1"", ""port"":""12345""}";
var _data2 = JsonSerializer.Deserialize<Configdata>(_data);
Console.WriteLine($"Content: {_data2.ip}");
Console.WriteLine($"Content: {_data2.port}");
c++

public struct Configdata
{
public string ip { get; set; }
public string port { get; set; }
}

string _data = @"{""ip"":""127.0.0.1"", ""port"":""12345""}";
var _data2 = JsonSerializer.Deserialize<Configdata>(_data);
Console.WriteLine($"Content: {_data2.ip}");
Console.WriteLine($"Content: {_data2.port}");
AAccord2/1/2023
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.

Looking for more? Join the community!