如何在c#中读取基于索引的json并将其转换为对象?

时间:2015-12-30 05:01:39

标签: c# json serialization asp.net-mvc-5

这是消费Web服务的MVC 5应用程序。具有以下格式返回字符串的JSON数据的方法的Web服务。

 [WebMethod]
 [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
 public string GetCompanyData()
 {
        string jsonData = "[{\"1\":\"Message-Type\"},{\"28\":\"KEM\",\"3\":\"COMPANY1\",\"6\":\"218\",\"21\":\"6.8\",\"14\":\"33543\",\"16\":\"7188572.3\"},";
        jsonData +="{\"28\":\"KEM\",\"3\":\"COMPANY2\",\"6\":\"224.5\",\"21\":\"4.5\",\"14\":\"19058\",\"16\":\"4246936\"},";
        jsonData +="{\"28\":\"KEM\",\"3\":\"COMPANY3\",\"6\":\"79.9\",\"21\":\"3.4\",\"14\":\"81418\",\"16\":\"6320237.5\"},";
        jsonData +="{\"28\":\"KEM\",\"3\":\"COMPANY4\",\"6\":\"87\",\"21\":\"2.5\",\"14\":\"42277\",\"16\":\"3654459\"},";
        jsonData +="{\"28\":\"KEM\",\"3\":\"COMPANY5\",\"6\":\"103\",\"21\":\"2.3\",\"14\":\"1735\",\"16\":\"177450.4\"},";
        jsonData +="{\"28\":\"KEM\",\"3\":\"COMPANY6\",\"6\":\"108.1\",\"21\":\"2.1\",\"14\":\"269165\",\"16\":\"29039148.4\"},";
        jsonData +="{\"28\":\"KEM\",\"3\":\"COMPANY7\",\"6\":\"95.9\",\"21\":\"1.2\",\"14\":\"313\",\"16\":\"29479.7\"},";
        jsonData +="{\"28\":\"KEM\",\"3\":\"COMPANY8\",\"6\":\"51.1\",\"21\":\"1\",\"14\":\"117208\",\"16\":\"5954460.6\"},";
        jsonData +="{\"28\":\"KEM\",\"3\":\"COMPANY9\",\"6\":\"73.6\",\"21\":\"0.9\",\"14\":\"161593\",\"16\":\"11856197.6\"},";
        jsonData +="{\"28\":\"KEM\",\"3\":\"COMPANY10\",\"6\":\"40.1\",\"21\":\"0.55\",\"14\":\"220241\",\"16\":\"8782243.3\"}]";
        return jsonData;
  }

尝试将其转换为对象列表。

 In controller :
  JavaScriptSerializer json_serializer = new JavaScriptSerializer();
  var companyDataList = json_serializer.Deserialize<List<object>>(svc.GetCompanyData())

这很好用。但是在JSON中存在迭代,需要对自定义对象执行拆箱操作。由于键是基于整数的,无法从JSON读取数据。 但是生成JSON是将int作为键,因此无法读取特定数据。 如何阅读这样的JSON数据。 编辑:尝试与牛顿软件

object[] objectArray = JsonConvert.DeserializeObject<object[]>(JsonConvert.SerializeObject(companyDataList ));

但基础数据列表导致立即窗口(首先):

objIndex
{
  "28": "KEM",
  "3": "COMPANY1",
  "6": "218",
  "21": "6.8",
  "14": "33543",
  "16": "7188572.3"
}
    base: {
  "28": "KEM",
  "3": "COMPANY1",
  "6": "218",
  "21": "6.8",
  "14": "33543",
  "16": "7188572.3"
}
    Type: Object

解答:

添加了以下要扩展的类:

 public static class Extensions
    {
        public static T ToObject<T>(this IDictionary<string, object> source, Dictionary<string, string> sourceDictionary)
          where T : class, new()
        {
            T someObject = new T();
            Type someObjectType = someObject.GetType();

            foreach (KeyValuePair<string, object> item in source)
            {
                if (sourceDictionary.Keys.Contains(item.Key) && (someObjectType.GetProperty(sourceDictionary[item.Key])!=null))
                    someObjectType.GetProperty(sourceDictionary[item.Key]).SetValue(someObject, item.Value, null);
            }
            return someObject;
        }

        public static IDictionary<string, object> AsDictionary(this object source, BindingFlags bindingAttr = BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance)
        {
            return source.GetType().GetProperties(bindingAttr).ToDictionary
            (
                propInfo => propInfo.Name,
                propInfo => propInfo.GetValue(source, null)
            );

        }
    } 

在Class方法中使用它作为:

var tempObjArray = json_serializer.Deserialize<object[]>(svc.GetTopByVolume());
        List<Symbol> topByVolumeList = new List<Symbol>();
        foreach (object tmpObject in tempObjArray)
        {
            Dictionary<string, object> diTopByVolumes = (Dictionary<string, object>)tmpObject;
            Symbol someObject = diTopByVolumes.ToObject<Symbol>(StaticDictionary.TopByVolumeDictionary);
            topByVolumeList.Add(someObject);
        }

也在Global.asax中指定的应用程序启动事件中添加:

     public static Dictionary<string, string> TopByVolumeDictionary = new Dictionary<string, string>();
 TopByVolumeDictionary.Add("3", "SYMBOLID");
            TopByVolumeDictionary.Add("6", "Property1");
            TopByVolumeDictionary.Add("14", "Property2");
            TopByVolumeDictionary.Add("16", "Property3");
            TopByVolumeDictionary.Add("21", "Property4");

1 个答案:

答案 0 :(得分:1)

稍微扩展我的评论,

你可能最好建立一个反映你的JSON应该是什么样子的简单类或对象,然后创建一个reactive()你可以转换为JSON字符串。

可能无法反映您想要的结构的快速示例如下:

班级:

List<companyObject>

然后是一个小代码(不优雅)

public class Company
{
    public Dictionary<string, string> companyObject = 
        new Dictionary<string, string>();
    public Dictionary<string, string> 
        Add(string twentyEight, string three, string six,
        string twentOne, string fourteen, string sixteen)
    {
        companyObject.Add("28", twentyEight);
        companyObject.Add("3", three);
        companyObject.Add("6", six);
        companyObject.Add("21", twentOne);
        companyObject.Add("14", fourteen);
        companyObject.Add("16", sixteen);
        return companyObject;
    }
}

会创建一个类似于:

的JSON
List<Company> companyList = new List<Company>();
Company c = new Company();
c.Add("KEM", "COMPANY1", "218", "6.8", "33543", "7188572.3");
companyList.Add(c);

string newJson = Newtonsoft.Json.JsonConvert.SerializeObject(companyList);

两个项目的列表如下:

[{"companyObject":{"28":"KEM","3":"COMPANY1","6":"218","21":"6.8",
"14":"33543","16":"7188572.3"}}]

我会根据你真正想要的内容调整课程,但作为一个快速粗略的概念,我认为这是一种更好的方法。