将嵌套的 c# 类型转换为 json,并在 javascript 中使用它
本文关键字:javascript 并在 json 嵌套 类型转换 | 更新日期: 2023-09-27 18:35:20
我有一个C#
类作为应用程序使用的常量值的容器。
public abstract class MyConstants
{
public abstract class HttpMethods
{
public const string Put = "PUT";
public const string Post = "POST";
public const string Get = "GET";
}
public abstract class ContainerKeys
{
public abstract class GlobalModal
{
public const string DialogId = "6698CB2F-2948-45D9-8902-2C13A7ED6335";
}
}
public const int MaximumImageUploadSize = 3 * 1024 * 1024; // 3MB
public const int MaximumDocumentUploadSize = 5 * 1024 * 1024; // 5MB
}
如何将其转换为 json,然后将其复制到内部的 javascript
-文件中以像javascript
内部MyConstants.HttpMethods.Put
一样使用它?
用
var constants = typeof(MyConstants).GetFields().ToDictionary(x => x.Name, x => x.GetValue(null));
var json = new JavaScriptSerializer().Serialize(constants);
return JavaScript(json + ";");
仅返回没有所有嵌套类/常量的{"MaximumImageUploadSize":3145728,"MaximumDocumentUploadSize":5242880};
。
这个问题似乎更多地与在具有多个嵌套其他Type
的Type
上使用反射有关。
您的MyConstants
类中没有类的实例。这就是为什么它不可见的原因。
简化示例如下:
public abstract class MyConstants
{
public class HttpMethods
{
public const string Put = "PUT";
public const string Post = "POST";
public const string Get = "GET";
}
public const int MaximumImageUploadSize = 3 * 1024 * 1024; // 3MB
public const int MaximumDocumentUploadSize = 5 * 1024 * 1024; // 5MB
public const HttpMethods HttpMethodObj;
}
你需要递归来构建字典:
例
Dictionary<string, object> TypeToDictionary(Type type)
{
var ret = type.GetFields().ToDictionary(x => x.Name, x => x.GetValue(null));
foreach (var nestedType in type.GetNestedTypes())
{
ret.Add(nestedType.Name, TypeToDictionary(nestedType));
}
return ret;
}
用法
var dictionary = TypeToDictionary(typeof(MyConstants));
var json = JsonConvert.SerializeObject(dictionary, Newtonsoft.Json.Formatting.Indented);
输出
{
"MaximumImageUploadSize": 3145728,
"MaximumDocumentUploadSize": 5242880,
"HttpMethods": {
"Put": "PUT",
"Post": "POST",
"Get": "GET"
},
"ContainerKeys": {
"GlobalModal": {
"DialogId": "6698CB2F-2948-45D9-8902-2C13A7ED6335"
}
}
}
注意
我用过Newtonsoft.JSON
但JavaScriptSerializer
也应该有效。