简体   繁体   English

解析Json .Net Web Api

[英]Parsing Json .Net Web Api

I'm new with Web API 2 / Entity Framework 6 project, I'm making REST services, but for one specific service I'm going to receive (via Post) a JSON before making any CRUD operations over any entity of the model, (have to make some business validations over the data, add or complement some things and decide on wich entity to save), the JSON is: 我是Web API 2 / Entity Framework 6项目的新手,正在制作REST服务,但是对于一个特定的服务,我将在对模型的任何实体进行任何CRUD操作之前(通过Post)接收JSON, (必须对数据进行一些业务验证,添加或补充一些内容并决定要保存的夹心实体),JSON是:

{
    "head": {
        "action": "create",
        "object": "oneobject",
        "user": "theuser"
    },
    "object": {
        "name1": "a name 1",
        "name2": "a name 2",
        "description": "a description here"
    },
    "rule": [{
        "name": "any name",
        "value": "any value"
    }, {
        "name": "another name",
        "value": "another value"
    }]
}

So the json not maps directly to an entity, in fact I have no model or object for this. 所以json不能直接映射到实体,实际上我没有为此的模型或对象。 What would be the better way to work with it? 有什么更好的方法来使用它? I mean how to receive and parse the json. 我的意思是如何接收和解析json。 I'm new with web api and rest services, and I would appreciate you can help me and explain me with good details. 我是Web api和Rest服务的新手,希望您能为我提供帮助,并向我详细解释。 Thanks guys. 多谢你们。

Edit: 编辑:

  1. Any idea of the POCO or class that match this kind of json. 与这种json匹配的POCO或类的任何想法。 ("rule" list It's variable, can be one or more). (“规则”列表是可变的,可以是一个或多个)。

  2. After create this poco or class I would have to make a controller based on this? 创建了这个poco或类之后,我将不得不基于此创建一个控制器?

As others have said, what you need is a POCO object to represent your request. 正如其他人所说,您需要一个POCO对象来表示您的请求。 Based on the information you have provided the following should achieve close enough to what you are after: 根据您提供的信息,以下各项应该可以实现与所达到的目标足够接近的效果:

public enum CrudAction
{
    Create,
    Read,
    Update,
    Delete
}

public sealed class CrudRequestHeader
{
    public CrudAction Action { get; set; }

    public string Object { get; set; }

    public string User { get; set; }
}

public sealed class RuleDefinition
{
    public string Name { get; set; }

    public string Value { get; set; }
}

public sealed class CrudRequest
{
    public CrudRequestHeader Head { get; set;}

    public Dictionary<string, string> Object { get; set; }

    public List<RuleDefinition> Rule { get; set; }
}

In your Web API controller method you can then take a parameter of type CrudRequest and your JSON will be deserialized to this object, eg: 然后,在Web API控制器方法中,可以采用类型CrudRequest的参数,并且JSON将反序列化到该对象,例如:

public IHttpActionResult Post(CrudRequest crudRequest)
{
    // TODO Implementation
}

You may notice I have used Dictionary<string, string> for CrudRequest.Object as it is variable how many key/values we will be supplied with, I have made the assumption that all values are strings, you can use an object value if you prefer but you will then need to handle the type of value. 您可能会注意到我为CrudRequest.Object使用了Dictionary<string, string> ,因为它是可变的,我们将提供多少个键/值,我假设所有值都是字符串,如果您可以使用object值更喜欢,但是您将需要处理值的类型。 In the same principle I have used List<RuleDefinition> for CrudRequest.Rule to cater for the variable number of rules which may be supplied. 按照相同的原则,我为CrudRequest.Rule使用List<RuleDefinition>来满足可能提供的可变数量的规则。

A LINQPad sample containing the above definitions and use with your input can be found here: http://share.linqpad.net/7rvmhh.linq 包含上述定义并与您的输入配合使用的LINQPad示例可在以下位置找到: http : //share.linqpad.net/7rvmhh.linq

Although the JSON may not represent a logical entity in your model, you clearly have a mental model of the "shape" of the JSON data - I say this because you define it in your code snippet. 尽管JSON可能无法在您的模型中表示逻辑实体,但是您显然拥有一个JSON数据“形状”的思维模型-之所以这样说是因为您在代码段中定义了它。 You should create a POCO (plain old C# object) to represent this model, and deserialize the incoming JSON request to an object of that type. 您应该创建一个POCO(普通的C#对象)来表示该模型,然后将传入的JSON请求反序列化为该类型的对象。 Once you've deserialized it to your object, it will be trivial to work with this data using object properties and such. 将其反序列化为对象后,使用对象属性等使用此数据将变得很简单。

The best thing to do would be to create a class that models the object you expect back. 最好的办法是创建一个对您期望返回的对象进行建模的类。

This way in your Web API method you can use the [FromBody] attribute to automatically parse the body of the request. 这样,在Web API方法中,您可以使用[FromBody]属性来自动解析请求的正文。

Example - 范例-

Your data contract would look like this: 您的数据合同如下所示:

public class MyContract
{
  public string MyData { get; set;} 
}

In your ApiController 在您的ApiController中

[HttpPost]
[Route("api/myobject")]
public async Task ReceiveMyObject([FromBody]MyContract object) {

  var data = object.MyData;
  // Do whatever you need to do here.
}

This may seem tedious but this will let you keep your code organized. 这看起来很乏味,但是这可以使您的代码井井有条。

Edit So to create a contract out of this: 编辑 So以此创建合同:

{
    "head": {
        "action": "create",
        "object": "oneobject",
        "user": "theuser"
   },
    "object": {
        "name1": "a name 1",
        "name2": "a name 2",
        "description": "a description here"
    },
    "rule": [{
        "name": "any name",
        "value": "any value"
    }, {
        "name": "another name",
        "value": "another value"
    }]
} 

You would do something like this: 您将执行以下操作:

public class MyContract 
{
    [JsonProperty("head")]
    public MetaObject Head 
    {
        get; set;
    }

    // Not sure if this will work, but it probably will
    [JsonProperty("object")]
    public JObject ExtendedInformation
    {
        get;
        set;
    }

    [JsonProperty("rule")]
    public Rule[] Rules 
    {
        get;
        set;
    }
}

// "MetaObject" definition omitted but you can understand my point with the below

public class Rule
{
    [JsonProperty("name")]
    public string Name
    {
        get;
        set;
    }

    [JsonProperty("value")]
    public string Value
    {
        get;
        set;
    }
}

Usually a REST service issue a contract, which means some kind of metadata to describe the content of its messages, otherwise you cannot call this as a RESTful Web API. 通常,REST服务签发合同,这意味着某种元数据来描述其消息的内容,否则您不能将其称为RESTful Web API。 Take a look at this post from Roy Fielding, who created the term of REST API, if you want to know better what is REST and what is not. 如果您想更好地了解什么是REST,什么不是,那么请看一下创建REST API术语的Roy Fielding的这篇文章

So if your service is a true REST service you should be able to have a description somewhere that give you the possibility to parse the media. 因此,如果您的服务是真正的REST服务,则应该可以在某处进行描述,从而使您可以解析媒体。

However, if you still cannot find any way to understand how the JSON should be interpreted you may be able to use it inside a C# class anyway: take a look at the JObject class from Newtonsoft.Json that enables to use a dynamic object at runtime. 但是,如果仍然找不到任何方法来理解应该如何解释JSON,则无论如何都可以在C#类中使用它:看一下Newtonsoft.Json的JObject类,该类可以在运行时使用动态对象。 。

Basically, it is used like this: 基本上,它是这样使用的:

using Newtonsoft.Json.Linq; // This needs the Newtonsoft.Json package

dynamic entity = JObject.Parse(jsonString);

string value = entity.key1;
string value2 = entity["key2"];

I did this simple demo with your data. 我用您的数据做了这个简单的演示

You can also check the full documentation of the class on the Newtonsoft website. 您也可以在Newtonsoft网站上查看该类的完整文档。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM