簡體   English   中英

在 C# 中遍歷 JSON 對象

[英]Iterating over JSON object in C#

我在 C# 中使用 JSON.NET 來解析來自 Klout API 的響應。 我的回應是這樣的:

[
  {
    "id": "5241585099662481339",
    "displayName": "Music",
    "name": "music",
    "slug": "music",
    "imageUrl": "http://kcdn3.klout.com/static/images/music-1333561300502.png"
  },
  {
    "id": "6953585193220490118",
    "displayName": "Celebrities",
    "name": "celebrities",
    "slug": "celebrities",
    "imageUrl": "http://kcdn3.klout.com/static/images/topics/celebrities_b32741b6703151cc7bd85fba24c44c52.png"
  },
  {
    "id": "5757029936226020304",
    "displayName": "Entertainment",
    "name": "entertainment",
    "slug": "entertainment",
    "imageUrl": "http://kcdn3.klout.com/static/images/topics/Entertainment_7002e5d2316e85a2ff004fafa017ff44.png"
  },
  {
    "id": "3718",
    "displayName": "Saturday Night Live",
    "name": "saturday night live",
    "slug": "saturday-night-live",
    "imageUrl": "http://kcdn3.klout.com/static/images/icons/generic-topic.png"
  },
  {
    "id": "8113008320053776960",
    "displayName": "Hollywood",
    "name": "hollywood",
    "slug": "hollywood",
    "imageUrl": "http://kcdn3.klout.com/static/images/topics/hollywood_9eccd1f7f83f067cb9aa2b491cd461f3.png"
  }
]

如您所見,它包含 5 個id標簽。 也許下一次它會是 6 或 1 或其他一些數字。 我想遍歷 JSON 並獲取每個id標簽的值。 我不能在不知道會有多少的情況下運行一個循環。 我該如何解決這個問題?

dynamic dynJson = JsonConvert.DeserializeObject(json);
foreach (var item in dynJson)
{
    Console.WriteLine("{0} {1} {2} {3}\n", item.id, item.displayName, 
        item.slug, item.imageUrl);
}

要么

var list = JsonConvert.DeserializeObject<List<MyItem>>(json);

public class MyItem
{
    public string id;
    public string displayName;
    public string name;
    public string slug;
    public string imageUrl;
}

您可以使用JsonTextReader讀取 JSON 並遍歷標記:

using (var reader = new JsonTextReader(new StringReader(jsonText)))
{
    while (reader.Read())
    {
        Console.WriteLine("{0} - {1} - {2}", 
                          reader.TokenType, reader.ValueType, reader.Value);
    }
}

這對我有用,轉換為嵌套的 JSON 以易於閱讀 YAML

    string JSONDeserialized {get; set;}
    public int indentLevel;

    private bool JSONDictionarytoYAML(Dictionary<string, object> dict)
    {
        bool bSuccess = false;
        indentLevel++;

        foreach (string strKey in dict.Keys)
        {
            string strOutput = "".PadLeft(indentLevel * 3) + strKey + ":";
            JSONDeserialized+="\r\n" + strOutput;

            object o = dict[strKey];
            if (o is Dictionary<string, object>)
            {
                JSONDictionarytoYAML((Dictionary<string, object>)o);
            }
            else if (o is ArrayList)
            {
                foreach (object oChild in ((ArrayList)o))
                {
                    if (oChild is string)
                    {
                        strOutput = ((string)oChild);
                        JSONDeserialized += strOutput + ",";
                    }
                    else if (oChild is Dictionary<string, object>)
                    {
                        JSONDictionarytoYAML((Dictionary<string, object>)oChild);
                        JSONDeserialized += "\r\n";  
                    }
                }
            }
            else
            {
                strOutput = o.ToString();
                JSONDeserialized += strOutput;
            }
        }

        indentLevel--;

        return bSuccess;

    }

用法

        Dictionary<string, object> JSONDic = new Dictionary<string, object>();
        JavaScriptSerializer js = new JavaScriptSerializer();

          try {

            JSONDic = js.Deserialize<Dictionary<string, object>>(inString);
            JSONDeserialized = "";

            indentLevel = 0;
            DisplayDictionary(JSONDic); 

            return JSONDeserialized;

        }
        catch (Exception)
        {
            return "Could not parse input JSON string";
        }

我正在嘗試迭代數組中的Json,當我嘗試迭代Json中提供的db的列的值時,我無法解析它,是在做其他事情還是跳過了一步?

/ {“實體”:[{“ LogicalName”:“ cmtx_ejecutivo”,“ Id”:“ d96b7fa3-9972-e911-80d6-000c29edc98a”,“屬性”:[{“鍵”:“ cmtx_rut”,“值”: 13728165},{“密鑰”:“ cmtx_name”,“值”:“ Andrea Saez Caldera”},{“密鑰”:“ cmtx_email”,“值”:“ uasaez@bancochile.cl”},{“密鑰”: “ cmtx_ejecutivoid”,“值”:“ d96b7fa3-9972-e911-80d6-000c29edc98a”}],“ EntityState”:空,“ FormattedValues”:[{“鍵”:“ cmtx_rut”,“值”:“ 13.728.165 “}],” RelatedEntities“:[]}],” MoreRecords“:否,” PagingCookie“:”“,” MinActiveRowVersion“:” -1“,” TotalRecordCount“:-1,” TotalRecordCountLimitExceeded“:否,” EntityName “:” cmtx_ejecutivo“} /

“ Este es El Json que intento iterar para crear un ticket post obteniendo los datos,pero no paso de la iteracion”

Este es el metodo:

私人動態postCreateTicket([FromBody]動態值,字符串域){字符串CAMPO_MEDIO = ConfigurationSettings.AppSettings [“ cl.banchile”。 +域+“ .ticket.campoMedio”]; 字符串CAMPO_CANAL = ConfigurationSettings.AppSettings [“ cl.banchile”。 +網域+“ .ticket.campoCanal”]; 字符串CAMPO_TELEFONO = ConfigurationSettings.AppSettings [“ cl.banchile”。 +域+“ .ticket.campoTelefono”]; 字符串CAMPO_RUT = ConfigurationSettings.AppSettings [“ cl.banchile”。 +域+“ .ticket.campoRut”]; 字符串CAMPO_FROM_TELEFONICO = ConfigurationSettings.AppSettings [“ cl.banchile”。 +域+“ .ticket.FormTelefonico”];

        EjecutivoZendeskResult result = new EjecutivoZendeskResult();

        string remoteSurveyUrl = builCreateTicketUrl(domain);
        string autorizationValue = buildTokenZendesk(domain);


        dynamic message = new System.Dynamic.ExpandoObject();
        dynamic ticket = new System.Dynamic.ExpandoObject();

        dynamic comment = new System.Dynamic.ExpandoObject();
        dynamic body = new System.Dynamic.ExpandoObject();

        dynamic attributes = new System.Dynamic.ExpandoObject();
        dynamic entities = new System.Dynamic.ExpandoObject();
        List<dynamic> fields = new List<dynamic>();

        //dynamic value = null; //JsonConvert.DeserializeObject(value);
         foreach (var item in value.Entities)
         {
             EjecutivoJson jsonEjecutivo = new EjecutivoJson();

             jsonEjecutivo.nombre = (item["cmtx_name"]).ToString();
             jsonEjecutivo.campoRut = long.Parse(item["cmtx_rut"].ToString());
             jsonEjecutivo.email = (item["cmtx_email"] == null ? jsonEjecutivo.campoRut + EJECUTIVO_SIN_MAIL : (item["cmtx_email"]).ToString().Replace(char.ConvertFromUtf32(160), " "));
             //crear model con patrones de ingreso del JSon y setearlos ahi
         }

        dynamic campoRut = new ExpandoObject();
        campoRut.id = CAMPO_RUT;
        //campoRut.value = "11794959";
        campoRut.value = value.Entities[0].Attributes;

        dynamic campoMedio = new ExpandoObject();
        campoMedio.id = CAMPO_MEDIO;
        campoMedio.value = "telefono";

        dynamic campoCanal = new ExpandoObject();
        campoCanal.id = CAMPO_CANAL;
        campoCanal.value = "_ivr";

        dynamic campoTelefono = new ExpandoObject();
        campoTelefono.id = CAMPO_TELEFONO;
        campoTelefono.value = value.campoTelefono;
        ;

        fields.Add(campoRut);
        fields.Add(campoMedio);
        fields.Add(campoCanal);
        fields.Add(campoTelefono);

        ticket.subject = "Llamada Cliente -  " + campoRut;
        string str_comment = "Llamada entrante\n\nTelefono: " + campoTelefono + " \nHora: " + value.body.time + "\nRut: " + campoRut;
        string html_comment = "<p><strong>Llamada entrante</strong></p><p>Telefono : " + campoTelefono + "</p><p>Hora : " + value.body.time + "</p><p>Rut : " + campoRut + "</p>";
        comment.html_body = html_comment;
        AddProperty(comment, "public", false);

        ticket.comment = comment;
        ticket.fields = fields;
        ticket.ticket_form_id = CAMPO_FROM_TELEFONICO;

        List<string> tags = new List<string>();
        tags.Add("telefono_");
        tags.Add("ivr_");
        ticket.tags = tags;

        dynamic requester = new ExpandoObject();
        if (((string)value.body.customer.email).Length > 0)
        {
            requester.email = value.body.customer.email;
        }
        else
        {
            requester.email = campoRut + "cisco@";
        }
        requester.name = value.body.customer.name;

        ticket.requester = requester;
        ticket.metadata = value;
        ticket.external_id = value.body.messageId;
        ticket.is_public = true;

        message.ticket = ticket;

        string messagePut = JsonConvert.SerializeObject(message);

        ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
        System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(remoteSurveyUrl);
        request.ContentType = "application/json;charset=ISO-8859-1";
        request.Method = "POST";
        request.Headers.Add("Authorization", autorizationValue);
        request.Headers.Add(HttpRequestHeader.ContentEncoding, "ISO-8859-1");
        ProxyUtil.getProxy(ref request);


        System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
        byte[] byte1 = encoding.GetBytes(messagePut);
        request.ContentLength = byte1.Length;
        Stream newStream = request.GetRequestStream();
        newStream.Write(byte1, 0, byte1.Length);
        dynamic dobj = null;

        HttpWebResponse response = (HttpWebResponse)request.GetResponse();
        StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
        string responseString = reader.ReadToEnd();
        result.mensaje = responseString;

        JavaScriptSerializer jsonSerializer = new JavaScriptSerializer();
        dobj = jsonSerializer.Deserialize<dynamic>(responseString);

        return dobj;
    }

動漫卡通頭像簡約可愛小倉鼠頭像萌物表情包素材...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM