DataConstractJsonSerializer结合了两个JSON文件

时间:2017-07-13 07:40:00

标签: c# json datacontractjsonserializer

在挪威,他们有一个组织注册(brreg.no),您可以通过网络服务访问。如果组织拥有一个或多个其他组织,您还可以访问这些组织的列表。

现在我的问题是:我想为parrent组织创建一个类,并用DataContractJsonSerializer填充它。这个标准很简单。我还想做的是在父类中有一个List<ChildrenOrganisation>。如果parrent和子组织在同一个JSON文件中,这也很容易。但他们不是。有没有办法解决这个问题,可能合并两个不同的Streams

以下是我获取HTTP Web响应的方法:

public async Task GetHttpWebRespsoneAsJson(bool isSubOrganisation)
        {
            string href;
            string requestString;

            // Set the request string, depending on whether or not it is a sub-organisation
            if (isSubOrganisation)
            {
                href = "http://data.brreg.no/enhetsregisteret/underenhet.json?page=0&size=100&$filter=overordnetEnhet+eq+{0}";
                requestString = String.Format(href, organisationNumber);
            }
            else
            {
                href = "http://data.brreg.no/enhetsregisteret/enhet/{0}.json";
                requestString = String.Format(href, organisationNumber);
            }

            // Create the HTTP request, using the input parameters
            WebRequest httpRequest = WebRequest.Create(requestString);

            // Get the respone of the HTTP request
            httpResponse = await httpRequest.GetResponseAsync();

            // Get the statuscode (hopefully "OK")
            httpStatus = ((HttpWebResponse)httpResponse).StatusCode;
}

以下是DataContractJsonSerializer的实施方式:

public CompanyModel GetCompany()
{
    CompanyModel company = new CompanyModel();

    using (Stream httpDataStream = httpResponse.GetResponseStream())
    {
        DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(CompanyModel));
        company = (CompanyModel)ser.ReadObject(httpDataStream);
        httpDataStream.Close();
    }

    return company;
}

简化了上级组织(see an actual example here):

{
 "organisationId": 123,
 "name": "Parent Organisation",
 "address": {
   "streetname": "Electric Avenue",
   "number": 42,
   "city": "Los Angeles"
  }
}

简化了儿童组织列表(see an actual example here):

"organisations": [
  {
    "organisationId": 456,
    "parentOrganisation": 123,
    "name": "Children Organisation 1",
    "address": {
      "streetname": "Sunset Boulevard",
      "number": 69,
      "city": "San Fransisco"
    }
  },
  {
    "organisationId": 789,
    "parentOrganisation": 123,
    "name": "Children Organisation 2",
    "address": {
      "streetname": "Ocean Drive",
      "number": 13,
      "city": "Miami"
    }
  }
]

0 个答案:

没有答案