serialization shows only value kind and NOT the value

早过忘川 提交于 2021-01-20 12:20:28

问题


We have data coming from 3rd party system and I have one class designed like this,

 public class CollectionProperty
{
    public string Name { get; set; }
    public object Value { get; set; }
}

and my VS debugger saying value like this which gives me extra details of data type along with result,

Now when I serialize this using Newtonsoft,

 var x = JsonConvert.SerializeObject(resultPacket);

it's giving below output with only value kind and NOT the value.

I need string value with double quote, number value withOUT double quote, how to do this?

[{"Name":"Device ID","Value":{"ValueKind":3}}]},{"Name":"CPU0","CollectionProperties":[{"Name":"CPU Load Percentage","Value":{"ValueKind":4}}]}]


回答1:


Assuming this is a valid incoming json,

[{"Name":"CPU Load Percentage","Value":{"ValueKind":4}}]

Change your class to look like this. You can change the class /property name as per your need. Json Attribute is to map your property with incoming JSON property. Also, you can use dynamic or JObject if your incoming JSON property can change in future. If it wont, you can use the code below:

        public class Value    {
            [JsonProperty("ValueKind")]
            public int ValueKind; 
        }
    
        public class SystemData{
            [JsonProperty("Name")]
            public string Name; 
    
            [JsonProperty("Value")]
            public Value Value; 
        }
    
//Your root class. 
        public class CollectionProperty{
           
            public List<SystemData> SystemDataList; 
        }

Update

Since your json has [{}] that means , its an array or collection of complex objects. {} = class so it seems, there comes a list of class with two properties Name and Value in which again Value is a class or complex object with a property ValueKind of type int.

Usage

CollectionProperty myDeserializedClass = JsonConvert.DeserializeObject<CollectionProperty>(myJsonResponse);


来源:https://stackoverflow.com/questions/65235688/serialization-shows-only-value-kind-and-not-the-value

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!