简体   繁体   English

在 C# 中遍历 JSON 对象

[英]Iterating over JSON object in C#

I am using JSON.NET in C# to parse a response from the Klout API.我在 C# 中使用 JSON.NET 来解析来自 Klout API 的响应。 My response is like this:我的回应是这样的:

[
  {
    "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"
  }
]

As you see, it contains 5 id tags.如您所见,它包含 5 个id标签。 Maybe next time it would be 6 or 1 or some other number.也许下一次它会是 6 或 1 或其他一些数字。 I want to iterate over the JSON and get the value of each id tag.我想遍历 JSON 并获取每个id标签的值。 I can't run a loop without knowing how many there will be.我不能在不知道会有多少的情况下运行一个循环。 How can I solve this?我该如何解决这个问题?

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);
}

or要么

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;
}

You can use the JsonTextReader to read the JSON and iterate over the tokens:您可以使用JsonTextReader读取 JSON 并遍历标记:

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

This worked for me, converts to nested JSON to easy to read YAML这对我有用,转换为嵌套的 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;

    }

usage用法

        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";
        }

I'm trying to iterate a Json, which comes within an array, when I try to iterate the value of the column of the db that comes in Json, I can't parse it, am I doing something else or skip a step? 我正在尝试迭代数组中的Json,当我尝试迭代Json中提供的db的列的值时,我无法解析它,是在做其他事情还是跳过了一步?

/ { "Entities": [{"LogicalName": "cmtx_ejecutivo","Id": "d96b7fa3-9972-e911-80d6-000c29edc98a", "Attributes": [ { "Key": "cmtx_rut", "Value": 13728165 }, { "Key": "cmtx_name", "Value": " Andrea Saez Caldera" }, { "Key": "cmtx_email", "Value": "uasaez@bancochile.cl" }, { "Key": "cmtx_ejecutivoid", "Value": "d96b7fa3-9972-e911-80d6-000c29edc98a" } ], "EntityState": null, "FormattedValues": [ { "Key": "cmtx_rut", "Value": "13.728.165" } ], "RelatedEntities": [] } ], "MoreRecords": false, "PagingCookie": "", "MinActiveRowVersion": "-1", "TotalRecordCount": -1, "TotalRecordCountLimitExceeded": false, "EntityName": "cmtx_ejecutivo" } / / {“实体”:[{“ 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 Json que intento iterar para crear un ticket post obteniendo los datos,pero no paso de la iteracion”

Este es el metodo : Este es el metodo:

private dynamic postCreateTicket([FromBody]dynamic value, string domain) { string CAMPO_MEDIO = ConfigurationSettings.AppSettings["cl.banchile." 私人动态postCreateTicket([FromBody]动态值,字符串域){字符串CAMPO_MEDIO = ConfigurationSettings.AppSettings [“ cl.banchile”。 + domain + ".ticket.campoMedio"]; +域+“ .ticket.campoMedio”]; string CAMPO_CANAL = ConfigurationSettings.AppSettings["cl.banchile." 字符串CAMPO_CANAL = ConfigurationSettings.AppSettings [“ cl.banchile”。 + domain + ".ticket.campoCanal"]; +网域+“ .ticket.campoCanal”]; string CAMPO_TELEFONO = ConfigurationSettings.AppSettings["cl.banchile." 字符串CAMPO_TELEFONO = ConfigurationSettings.AppSettings [“ cl.banchile”。 + domain + ".ticket.campoTelefono"]; +域+“ .ticket.campoTelefono”]; string CAMPO_RUT = ConfigurationSettings.AppSettings["cl.banchile." 字符串CAMPO_RUT = ConfigurationSettings.AppSettings [“ cl.banchile”。 + domain + ".ticket.campoRut"]; +域+“ .ticket.campoRut”]; string CAMPO_FROM_TELEFONICO = ConfigurationSettings.AppSettings["cl.banchile." 字符串CAMPO_FROM_TELEFONICO = ConfigurationSettings.AppSettings [“ cl.banchile”。 + domain + ".ticket.FormTelefonico"]; +域+“ .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;
    }

Favor ayuda estoy pegado aqui... 动漫卡通头像简约可爱小仓鼠头像萌物表情包素材...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM