如何读取JSON数据不知道键值 [英] How to read the Json data without knowing the Key value

查看:607
本文介绍了如何读取JSON数据不知道键值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我这是作为输入字符串一个JSON数据。现在我需要更新与输入JSON数据现有的JSON数据。在我的情况,我想通过每个键和匹配与现有的JSON数据,然后更新输入JSON数据是关键的

code以检索现有的数据

  VAR existingJSon = ProductRepository.ListOfProd.Cast< JArray>()式(X =方式> X [PRODID]的ToString()== id.ToString()) ;

检索数据后,我existingJson看起来像下面。

  {
    PRODID:1,
    标题:C#,
    作者:杰菲
    发行人:XYZ,
    分类:微软
    }

现在我需要遍历每一个来作为输入和匹配现有的Json键和更新键值项。

输入和更新它应该是这样的后:

  {
PRODID:1,
标题:C#,
作者:杰菲
发行人:ABCD,
类别:Microsfot Basic .NET中开发工具包
}


解决方案

看看这可以帮助您,我们可以使用的 Newtonsoft 的反序列化未知类型和循环键和值。

 字符串的json ={PRODID:\\1 \\,标题:\\C#\\,作者:\\杰菲\\,出版社:\\XYZ \\,类别:\\微软\\};
        JObject的obj = JsonConvert.DeserializeObject< JObject>(JSON);
        变种属性= obj.Properties();
        的foreach(在性能VAR道具)
        {
            字符串键= prop.Name;
            对象值= prop.Value;
        }

I have a json data which comes as the input string. Now I need to update the existing Json data with the input Json data. In my case, I want to go through each key and match with existing Json data and then update the value of that Key with input Json data.

Code to retrive the existing data

var existingJSon = ProductRepository.ListOfProd.Cast<JArray>().Where(x => x["ProdId"].ToString() == id.ToString());

After retrieving the data my existingJson will look like below.

{
    ProdId:"1",
    Title:"C#",
    Author:"Jeffy",
    Publisher:"XYZ",
    Category:"Microsoft"
    }

Now I need to loop through every key that comes as the input and match to the existing Json key and update the value of that key.

Input and after updating it should look like this:

{
ProdId:"1",
Title:"C#",
Author:"Jeffy",
Publisher:"abcd",
Category:"Microsfot Basic .Net Development Kit"
}

解决方案

See if this helps you, We can use Newtonsoft to deserialize unknown types and loop the keys and values.

string json = "{ProdId:\"1\",Title:\"C#\",Author:\"Jeffy\",Publisher:\"XYZ\",Category:\"Microsoft\"}";
        JObject obj = JsonConvert.DeserializeObject < JObject>(json);
        var properties = obj.Properties();
        foreach (var prop in properties)
        {
            string key = prop.Name;
            object value = prop.Value;
        }

这篇关于如何读取JSON数据不知道键值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆