如何将json数据输入c#对象?

时间:2018-02-28 16:14:14

标签: c# json luis

以下是我的json输出类:

class PwdResetRequest
    {
        public class TopScoringIntent
        {
            public string intent { get; set; }
            public double score { get; set; }
        }

        public class Intent
        {
            public string intent { get; set; }
            public double score { get; set; }
        }

        public class Resolution
        {
            public string value { get; set; }
        }

        public class Entity
        {
            public string entity { get; set; }
            public string type { get; set; }
            public int startIndex { get; set; }
            public int endIndex { get; set; }
            public Resolution resolution { get; set; }
        }

        public class RootObject
        {
            public string query { get; set; }
            public TopScoringIntent topScoringIntent { get; set; }
            public List<Intent> intents { get; set; }
            public List<Entity> entities { get; set; }
        }

    }

Luis返回结果:

   {
  "query": "create a new password for sjao9841@demo.com",
  "topScoringIntent": {
    "intent": "ResetLANIDpassword",
    "score": 0.9956063
  },
  "intents": [
    {
      "intent": "ResetLANIDpassword",
      "score": 0.9956063
    },
    {
      "intent": "None",
      "score": 0.179328963
    }
  ],
  "entities": [
    {
      "entity": "sjao9841@demo.com",
      "type": "builtin.email",
      "startIndex": 26,
      "endIndex": 47
    }
  ]
}

我开发了以下用于从json获取数据的代码。

    var uri = 
    "https://westus.api.cognitive.microsoft.com/luis/v2.0/apps/" + 
    luisAppId + "?" + queryString;
    var response = await client.GetAsync(uri);

    var strResponseContent = await response.Content.ReadAsStringAsync();

    var json = await response.Content.ReadAsStringAsync();

    var token = JObject.Parse(json).SelectToken("entities");


    foreach (var item in token)
    {
        var request = item.ToObject<Entity>();
    } 

    // Display the JSON result from LUIS
    Console.WriteLine(strResponseContent.ToString());
}

我只想要来自&#34; TopScoringIntent&#34;的数据。我怎样才能使用C#获得它?下面是我尝试的代码,但没有出现: Message =从JsonReader读取JObject时出错。路径&#39;&#39;,第0行,第0位。 源= Newtonsoft.Json

2 个答案:

答案 0 :(得分:0)

我可能会错过你的意图,但如果你只关心特定的价值而不是整个javascript对象,你可以做以下事情。

dynamic json = JsonConvert.Deserialize(data);
var score = json.TopScoringIntent.Score;

这提供了TopScoringIntent内得分的具体值。显然,你也可以通过略微修改来构建一个集合。

foreach(var point in json.Intents)
     Console.WriteLine($"{point[1]} or {point.score}");

我相信这是您正在寻找的,从您的对象接收特定值。请注意动态是有用的,但这种方法相当快速和肮脏,可能不适合您的实现。

答案 1 :(得分:0)

quicktype为您的示例数据生成了以下C#类和JSON.Net编组代码:

// To parse this JSON data, add NuGet 'Newtonsoft.Json' then do:
//
//    using QuickType;
//
//    var pwdResetRequest = PwdResetRequest.FromJson(jsonString);

namespace QuickType
{
    using System;
    using System.Collections.Generic;
    using System.Net;

    using System.Globalization;
    using Newtonsoft.Json;
    using Newtonsoft.Json.Converters;
    using J = Newtonsoft.Json.JsonPropertyAttribute;

    public partial class PwdResetRequest
    {
        [J("query")]            public string Query { get; set; }          
        [J("topScoringIntent")] public Ntent TopScoringIntent { get; set; }
        [J("intents")]          public Ntent[] Intents { get; set; }       
        [J("entities")]         public Entity[] Entities { get; set; }     
    }

    public partial class Entity
    {
        [J("entity")]     public string EntityEntity { get; set; }
        [J("type")]       public string Type { get; set; }        
        [J("startIndex")] public long StartIndex { get; set; }    
        [J("endIndex")]   public long EndIndex { get; set; }      
    }

    public partial class Ntent
    {
        [J("intent")] public string Intent { get; set; }
        [J("score")]  public double Score { get; set; } 
    }

    public partial class PwdResetRequest
    {
        public static PwdResetRequest FromJson(string json) => JsonConvert.DeserializeObject<PwdResetRequest>(json, QuickType.Converter.Settings);
    }

    public static class Serialize
    {
        public static string ToJson(this PwdResetRequest self) => JsonConvert.SerializeObject(self, QuickType.Converter.Settings);
    }

    internal class Converter
    {
        public static readonly JsonSerializerSettings Settings = new JsonSerializerSettings
        {
            MetadataPropertyHandling = MetadataPropertyHandling.Ignore,
            DateParseHandling = DateParseHandling.None,
            Converters = { 
                new IsoDateTimeConverter()
                {
                    DateTimeStyles = DateTimeStyles.AssumeUniversal,
                },
            },
        };
    }
}

现在,您可以使用System.Linq获取Ntent之前的最大值Score

var uri = $"https://westus.api.cognitive.microsoft.com/luis/v2.0/apps/${luisAppId}?${queryString}";
var response = await client.GetAsync(uri);
var json = await response.Content.ReadAsStringAsync();
var request = PwdResetRequest.FromJson(json);

var maxIntent = request.Intents.MaxBy(intent => intent.Score);

Here's the generated code in a playground因此您可以更改类型名称和其他选项。