使用newtonsoft.json反序列化对象而不使用Class

时间:2015-11-17 20:54:37

标签: c# json json.net

我有这个Joson

{
  "Sucess": true,
  "Msg": "OK",
  "Ret": {
    "First": 0,
    "Next": true,
    "Total": 60,
    "Itens": [
      {
        "ID": 212121,
        "Name": "uuuuuuuuuuuuuuuuuuuuuuuu",
        "LcID": 9898,
        "Oclao": false,
        "Lal": {
          "ID": 12202,
          "Name": "pppppppppppppppppp",
          "Pais": "Brasil",
          "Dtc": 0.0
        },
        "Subtipo": {
          "ID": 7458,
          "Desc": "mnmnmnmnn"
        },
        "Tipo": {
          "Sit": "cor1",
          "Sitrm": 0,
          "Name": "Shsdfow"
        },
        "Qtde": 0,
        "Qntcoes": 0,
        "Pubum": "adfsdfsdfs",
        "Evias": {
          "arq": {
            "Mo": [
              "site.com"
            ],
            "Moir": [
              "site.com"
            ]
          }
        }
      },
      {
        "ID": 9797878,
        "Name": "uuuuuuuuuuuuuuuuuuuuuuuu",
        "LcID": 9898,
        "Oclao": false,
        "Lal": {
          "ID": 12332,
          "Name": "pppppppppppppppppp",
          "Pais": "Brasil",
          "Dtc": 0.0
        },
        "Subtipo": {
          "ID": 7458,
          "Desc": "mnmnmnmnn"
        },
        "Tipo": {
          "Sit": "cor1",
          "Sitrm": 0,
          "Name": "Shsdfow"
        },
        "Qtde": 0,
        "Qntcoes": 0,
        "Pubum": "adfsdfsdfs",
        "Evias": {
          "arq": {
            "Mo": [
              "site.com"
            ],
            "Moir": [
              "site.com"
            ]
          }
        }
      }
    ]
  }
}

我会阅读数组" items"通过字段名称而不使用类来反序列化,到目前为止我所做的是:

JObject jRetorno = JObject.Parse(strJson);
IList<JToken> jItens = jRetorno["Itens"].Children().ToList();

使用类的示例http://www.newtonsoft.com/json/help/html/SerializingJSONFragments.htm,因为我的json总是在变化,需要类似的东西:

strReturn = jItens[1]["ID"];
strReturn = jItens[1]["Name"];
strReturn = jItens[2]["ID"];
strReturn = jItens[2]["Name"];
strReturn = jItens[3]["ID"];
strReturn = jItens[3]["Name"];

谢谢!

1 个答案:

答案 0 :(得分:0)

你并不是那么遥远。您想要的数据在Ret对象内更低一级。试试这样:

JObject jRetorno = JObject.Parse(strJson);
IList<JToken> jItens = jRetorno["Ret"]["Itens"].Children().ToList();
foreach (JToken jt in jItens)
{
    Console.WriteLine(jt["ID"]);
    Console.WriteLine(jt["Name"]);
}

小提琴:https://dotnetfiddle.net/TwtGyz