You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用SimpleJson库解析JSON及转换特定JSON为强类型变量

Using SimpleJson in C#: Two Common Questions Answered

Hey there! Let’s break down your two SimpleJson questions with practical, runnable examples—no fluff, just what you need to get things working.


1. How to Parse JSON with SimpleJson

First things first: make sure you’ve got the SimpleJson library installed. You can grab it via NuGet Package Manager, or run this command in your terminal:

# .NET CLI
dotnet add package SimpleJson

# NuGet Package Manager Console
Install-Package SimpleJson

SimpleJson gives you a few flexible ways to parse JSON, depending on your needs:

Option 1: Parse to a Dynamic Object

Great if you don’t want to define a class upfront, or if the JSON structure is dynamic:

using SimpleJson;

string sampleJson = @"{""Username"": ""jdoe"", ""IsActive"": true, ""Score"": 95.5}";

// Parse to dynamic
dynamic parsedJson = SimpleJson.SimpleJson.Parse(sampleJson);

// Access properties directly
Console.WriteLine($"Username: {parsedJson.Username}");
Console.WriteLine($"Is Active: {parsedJson.IsActive}");
Console.WriteLine($"Score: {parsedJson.Score}");

Option 2: Parse to a Dictionary

Useful if you need to work with key-value pairs explicitly:

var jsonDict = SimpleJson.SimpleJson.DeserializeObject<Dictionary<string, object>>(sampleJson);

Console.WriteLine($"Username: {jsonDict["Username"]}");
Console.WriteLine($"Score: {jsonDict["Score"]}");

Option 3: Parse to a Strongly-Typed Class

Best practice for static JSON structures—creates clean, type-safe code:

// First define your class to match the JSON structure
public class UserProfile
{
    public string Username { get; set; }
    public bool IsActive { get; set; }
    public double Score { get; set; }
}

// Deserialize directly to your class
var userProfile = SimpleJson.SimpleJson.DeserializeObject<UserProfile>(sampleJson);

Console.WriteLine($"User: {userProfile.Username}, Active: {userProfile.IsActive}");

2. Convert the JSON Array ["login",{ "key":"value"}] to a Strongly-Typed Variable

This JSON is an array with two elements: a string (the operation name) and an object (the payload). Here’s how to map this to a clean, strongly-typed structure:

Step 1: Define Your Strongly-Typed Classes

First, create a class for the payload object, plus a wrapper class to hold both the operation and payload:

// Class to represent the payload object
public class LoginPayload
{
    public string Key { get; set; }
}

// Wrapper class to encapsulate the operation + payload
public class ApiOperation<T>
{
    public string OperationName { get; set; }
    public T Payload { get; set; }
}

Step 2: Parse and Map the JSON Array

You’ll first parse the array, then extract its elements and map them to your classes:

using SimpleJson;

string jsonArray = @"[""login"",{ ""key"":""value""}]";

// Parse the array into a list of objects
var jsonElements = SimpleJson.SimpleJson.DeserializeObject<IList<object>>(jsonArray);

// Map to your strongly-typed wrapper class
var loginOperation = new ApiOperation<LoginPayload>
{
    OperationName = jsonElements[0] as string,
    // Convert the second array element to your payload class
    Payload = SimpleJson.SimpleJson.DeserializeObject<LoginPayload>(jsonElements[1].ToString())
};

// Verify the result
Console.WriteLine($"Operation: {loginOperation.OperationName}");
Console.WriteLine($"Payload Key: {loginOperation.Payload.Key}");

Bonus: Using Dynamic for Simpler Access

If you prefer a more concise approach (without the IList), you can use dynamic:

dynamic parsedArray = SimpleJson.SimpleJson.Parse(jsonArray);

var loginOperationDynamic = new ApiOperation<LoginPayload>
{
    OperationName = parsedArray[0],
    Payload = SimpleJson.SimpleJson.DeserializeObject<LoginPayload>(
        SimpleJson.SimpleJson.SerializeObject(parsedArray[1])
    )
};

Just remember to add null checks in production code—for example, verifying that jsonElements[0] is indeed a string, and jsonElements[1] is a valid JSON object.


内容的提问来源于stack exchange,提问作者DeRibura

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 03:30:59