将对象从API转换为字符串C#

时间:2018-08-17 14:11:35

标签: c# json

我正在C#上为VK做一个机器人,但遇到了一些问题。我有这样的方法返回JSON

{
    "ts": 1674111105,
    "updates": [[4,
        2262,
        17,
        61835649,
        1534493714,
        "",
        {
            "attach1_type": "doc",
            "attach1": "61835649_472186415",
            "title": " ... "
        }
    ]]
}

正如我所见,这是对象,但是我无法获得从attach_type1title的任何东西,包括。这也是一个对象,无法像.ToString()一样转换为字符串,因为在这种情况下,结果是System.Object。因此,有人知道我可以如何更改此类型,还是不可能?我很绝望。

我为此对象创建了一个类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.Serialization;
namespace CSharpVKbot.VK.UserLongPoll
{
    [DataContract()]
    public class Attachment
    {
        [DataMember(Name = "attach1_type")]
        public string AttachType; 

        [DataMember(Name = "attach1")]
        public string Attach;

        [DataMember(Name = "title")]
        public string Title;
    }
}

创建了此类的对象

public Attachment DocId = new Attachment();

,然后尝试将类型更改为附件,但这也不起作用

case UpdateCode.NewMessage:
     u.MessageID = (int)item[1];
     u.Flags = (int)item[2];
     u.PeerID = (int)item[3];
     u.TimeStamp = (int)item[4];
     u.Text = (string)item[5];
     u.DocId = (Attachment)item[6];
     break;

4 个答案:

答案 0 :(得分:0)

我认为您将必须遍历所有json属性。

此代码可能会对您有所帮助

dynamic obj = Newtonsoft.Json.JsonConvert.DeserializeObject<dynamic>(YourJsonString);

foreach (var prop in obj)
{
   if (prop is Newtonsoft.Json.Linq.JObject)
   {
      // Handle JObject
   }

   if (prop is Newtonsoft.Json.Linq.JProperty)
   {
      // Handle JProperty
   }
}

答案 1 :(得分:0)

您需要反序列化JSON-不能仅将其转换为对象。

尝试类似

Attachment deserializedAttachement = new Attachment();  
MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(item[6]));  
DataContractJsonSerializer ser = new DataContractJsonSerializer(deserializedAttachment.GetType());  
deserializedAttachment = ser.ReadObject(ms) as Attachment;  
ms.Close();

item[6]是代表附件信息的字符串。

请参阅-https://docs.microsoft.com/en-us/dotnet/framework/wcf/feature-details/how-to-serialize-and-deserialize-json-data#example

答案 2 :(得分:0)

有很多指导来解决您的问题。 我喜欢(使用Newtonsoft):

JObject data = (JObject)JsonConvert.DeserializeObject(json);

var attach1_type = data.Descendants()
    .OfType<JProperty>()
    .FirstOrDefault(x => x.Name == "attach1_type")
    ?.Value;

答案 3 :(得分:0)

数字,字符串,对象位于同一数组中,这意味着它们在返回给您之前为boxed。因此您的updatesList<List<object>>object[][],无论如何。您的与该json格式匹配的c#类可能就像这样:

public class SomethingJsonResult
{
    public int ts { get; set; }

    public List<List<object>> updates { get; set; }
}

第一个选择是使用anonymous type

    public void ParseJsonResult(SomethingJsonResult result)
    {
        var definition = new
            {
                attach1_type = "",
                attach1 = "",
                title = ""
            };


        result?.updates?.ForEach(x =>
        {
            var update = JsonConvert.DeserializeAnonymousType(x[6], definition);
            var attachment = new Attachment
            {
                AttachType = update.attach1_type,
                Attach = update.attach1,
                Title = update.title,
            };
        });
    }

第二个选项有点复杂:

[DataContract()]
public class Attachment
{
    [DataMember(Name = "attach1_type")]
    [JsonProperty("attach1_type")] //Tell JsonConverter how to map your object
    public string AttachType { get; set; }//Here is property, but not variable

    [DataMember(Name = "attach1")]
    [JsonProperty("attach1")]
    public string Attach { get; set; }

    [DataMember(Name = "title")]
    [JsonProperty("title")]
    public string Title { get; set; }
}


    public void ParseJsonResult(SomethingJsonResult result)
    {
        result?.updates?.ForEach(update =>
        {
            //(Attachment)update[6] works only when your names of properties 100% match json objects
            JsonConvert.DeserializeObject<Attachment>(update[6])
            ....
        });
    }

DataContractSerializer示例: https://docs.microsoft.com/en-us/dotnet/api/system.runtime.serialization.datamemberattribute?redirectedfrom=MSDN&view=netframework-4.7.2

您可以在自定义转换器中实现所有功能: https://www.newtonsoft.com/json/help/html/CustomJsonConverter.htm

JsonConvert.DeserializeObject<AttachmentWrapper>(json, new AttachmentConverter(typeof(AttachmentWrapper)));