在C#中用非常大的JSON数组解析JSON。

问题描述 投票:0回答:1

我想把一个大的JSON数组解析成一个c#对象。现在我知道通常的方法是,你把一个类与JSON对象的匹配键相匹配,然后把JSON对象的每个值分配给c#类中的匹配键,但这对我的目的来说是非常低效的,因为我在处理非常大的JSON对象,这里是一个例子。

    [{
  "storeId": "331",
  "storeName": "Bergen, Lagunen",
  "status": "Open",
  "address": {
    "street": "Laguneveien 1",
    "postalCode": "5239",
    "city": "Rådal",
    "gpsCoord": "60.297116;5.331159",
    "globalLocationNumber": "7080003251008",
    "organisationNumber": "888039902"
  },
  "telephone": "22 01 50 00",
  "email": "[email protected]",
  "category": "6",
  "openingHours": {
    "regularHours": [{
      "dayOfTheWeek": "Monday",
      "openingTime": "10:00",
      "closingTime": "18:00",
      "closed": false
    }, {
      "dayOfTheWeek": "Tuesday",
      "openingTime": "10:00",
      "closingTime": "18:00",
      "closed": false
    }, {
      "dayOfTheWeek": "Wednesday",
      "openingTime": "10:00",
      "closingTime": "18:00",
      "closed": false
    }, {
      "dayOfTheWeek": "Thursday",
      "openingTime": "10:00",
      "closingTime": "18:00",
      "closed": false
    }, {
      "dayOfTheWeek": "Friday",
      "openingTime": "10:00",
      "closingTime": "18:00",
      "closed": false
    }, {
      "dayOfTheWeek": "Saturday",
      "openingTime": "10:00",
      "closingTime": "15:00",
      "closed": false
    }, {
      "dayOfTheWeek": "Sunday",
      "openingTime": "",
      "closingTime": "",
      "closed": true
    }],
    "exceptionHours": [{
      "date": "2020-05-21",
      "openingTime": "",
      "closingTime": "",
      "message": "Stengt Kristi himmelfartsdag"
    }]
  },
  "lastChanged": {
    "date": "2020-05-04",
    "time": "00:02:04"
  }
}]

有什么办法可以像在javascript中使用JSON.parse那样动态地把它变成一个c#对象?

c# json unity3d
1个回答
1
投票

你说你的json很大。我假设你这么说是因为json有很多你不需要的属性。如果你 需要所有的属性,我就会定义一个包含所有属性的类。

说到这里。如果我们要选择Newtonsoft.Json,我想你有两个真正的选择。

1. 定义一个只包含你需要的属性的类。

public class Pruned
{
    public string StoreId { get; set; }
}

var prunedList = JsonConvert.DeserializeObject<List<Pruned>>(myJsonString);

2. 反序列化为JArray,并将其作为一个动态对象。

var jArray = JArray.Parse(myJsonString);
var firstStoreId = jArray[0]["storeId"];
© www.soinside.com 2019 - 2024. All rights reserved.