根据属性值转换Json属性

时间:2015-01-12 09:34:39

标签: c# json

我想将json反序列化为object。 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; }
}

2 个答案:

答案 0 :(得分:0)

我在Java中用Gson库完成了这个,就像

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

我从记忆中写下了这段代码,所以不是100%可靠。如果不知道C#的任何解决方案。

答案 1 :(得分:-1)

$。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);

});