C
C#2y ago
entasy

❔ Convert JSON string to struct

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.
4 Replies
Thinker
Thinker2y ago
You can use System.Text.Json to do the deserialization, but I'm not sure it works with structs
Thinker
Thinker2y ago
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.
entasy
entasyOP2y ago
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}");
Accord
Accord2y ago
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.
Want results from more Discord servers?
Add your server