根据属性值转换 JSON 属性

本文关键字:属性 JSON 转换 | 更新日期: 2023-09-27 18:37:21

我想反序列化一个 json 来反对。json 如下所示。但是一个属性值可能是字符串或数组,有谁知道如何处理这个问题?

{
  "name": "123", //Name
  "properties": [
    {
      "propertyId": "Subject", // property id
      "value": [
        {
          "entityId": "math", //entity id
          "entityTypeId": "MATH" //entity type id 
        }
      ]
    },
    {
      "propertyId": "Description",
      "value": "Hello World."
    }
  ]
}

类如下所示。

//The object
public class Content
{
public Content()
{
//Properties is List.
Properties = new List<Property>();
}
[JsonProperty(PropertyName = "name")]
public string Name { get; set; }
[JsonProperty(PropertyName = "properties")]
public List<Property> Properties { get; set; }
}
public class Property
{
public Property()
{
Value = new List<Value>();
}
[JsonProperty(PropertyName = "propertyId")]
public string PropertyDefId { get; set; }
//Actually this property value can also be string, that's the problem.
[JsonProperty(PropertyName = "value")]
public List<Value> Value { get; set; }
}
//Value object
public class Value
{
//Have to write comments.
[JsonProperty(PropertyName = "entityId")]
public string EntityId { get; set; }
//Have to write comments.
[JsonProperty(PropertyName = "entityTypeId")]
public string EntityTypeId { get; set; }
}

根据属性值转换 JSON 属性

我已经用 Gson liblary 在 Java 中完成了这个,就像

JsonObject field = parser.parse(json).getElementAsJSONObject();
if (field.isPrimitive()) {
  String text = field.asString();
} else if (field.isArray()) {
  JSONArray array = field.asArray();
}

我根据我的记忆编写了这段代码,所以不是 100% 可靠。我不知道 C# 的任何解决方案。

$.parseJSON 会将您的字符串转换为正确的对象,即使两个不同属性的属性类型不同。

http://jsfiddle.net/mdanielc/e0acsyp1/2/

var jsonString = '{"name": "123","properties": [{"propertyId": "Subject","value": [{"entityId":"math","entityTypeId": "MATH" }]},{"propertyId": "Description","value": "Hello World."}]}';
var jsonobj = $.parseJSON(jsonString);
alert(jsonobj.properties[0].value[0].entityId);
alert(jsonobj.properties[1].value);

});