НаукаТеории

Сериализация объекта C# в JSON PostgreSQL

It looks like you’re asking for a C# example of an object class that can be serialized to JSON and then saved to a PostgreSQL database. I’ll assume you want a simple class, code to serialize it to JSON, and code to insert the JSON string into a PostgreSQL table. This uses Newtonsoft.Json for serialization (common library) and Npgsql for PostgreSQL connection.

For this to work, you’ll need:

  • .NET framework/library (e.g., .NET Core or Standard).
  • NuGet packages: Newtonsoft.Json and Npgsql.

Example C# Class

Here’s a simple example class that represents an object (e.g., a user profile). The class is plain-old CLR object (POCO), which is easily serializable.

using System;

public class UserProfile
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Email { get; set; }
    public DateTime CreatedAt { get; set; }

    // Constructor
    public UserProfile(int id, string name, string email)
    {
        Id = id;
        Name = name;
        Email = email;
        CreatedAt = DateTime.Now;
    }
}

Serializing to JSON

Use Newtonsoft.Json (or System.Text.Json in .NET Core 3.0+) to convert the object to a JSON string.

using Newtonsoft.Json;

// Create an instance
UserProfile user = new UserProfile(1, "John Doe", "john@example.com");

// Serialize to JSON
string jsonString = JsonConvert.SerializeObject(user);
Console.WriteLine(jsonString); // Outputs: {"Id":1,"Name":"John Doe","Email":"john@example.com","CreatedAt":"2025-12-17T17:29:27.000Z"}

For System.Text.Json, replace with:

using System.Text.Json;

string jsonString = JsonSerializer.Serialize(user);

Saving to PostgreSQL

Assume you have a PostgreSQL table like this (create it first if needed):

CREATE TABLE user_profiles (
id SERIAL PRIMARY KEY,
data JSONB -- Stores JSON data
);

Use Npgsql to connect and insert the JSON string.

using Npgsql;

// Connection string to your PostgreSQL DB
string connectionString = "Host=localhost;Username=your_user;Password=your_password;Database=your_db";

// Insert the JSON into the DB
using (var conn = new NpgsqlConnection(connectionString))
{
    conn.Open();

    using (var cmd = new NpgsqlCommand("INSERT INTO user_profiles (data) VALUES (@data)", conn))
    {
        cmd.Parameters.AddWithValue("data", jsonString);
        cmd.ExecuteNonQuery();
    }
}

Console.WriteLine("Data saved successfully!");

Notes

  • Deserialization: To read back, query the DB for JSON and deserialize: var user = JsonConvert.DeserializeObject<UserProfile>(jsonFromDB);.
  • Error Handling: Add try-catch for real-world use.
  • Alternatives: For ORM, consider Entity Framework Core with Npgsql provider to map objects directly to DB tables instead of JSON storage.
  • If this isn’t what you meant or you need more details (e.g., specific fields or async code), provide clarification!

What's your reaction?

Excited
0
Happy
0
In Love
0
Not Sure
0
Silly
0

Вам понравится

Смотрят также:Наука

Оставить комментарий