【问题标题】:how can I get json data in to the c# object?如何将 json 数据放入 c# 对象?
【发布时间】:2018-02-28 16:14:13
【问题描述】:

下面是我的 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; }
        }

    }

路易斯返回结果:

   {
  "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());
}

我只想要“TopScoringIntent”中的数据。我怎样才能使用 C# 获得它?以下是我尝试过的代码,但没有任何结果: 消息=从 JsonReader 读取 JObject 时出错。路径 '',第 0 行,第 0 位置。 Source=Newtonsoft.Json

【问题讨论】:

  • 我认为代码是'above'而不是'below',否则缺少代码......
  • TopScoringIntent 也不需要单独的类,它只是一个Intent
  • 如果你只想要来自topScoringIntent的数据,你为什么要遍历entities
  • 我正在尝试根据话语使用 luis 构建用于密码重置的 api。我需要存储 json 的值(最高得分意图到 c# 对象中)
  • 你在用C#开发,为什么不用微软提供的LUIS客户端库包呢? nuget.org/packages/Microsoft.Cognitive.LUIS 您将拥有所有必要的对象来进行处理,而不是手动实现 http 调用并生成包中已经存在的类;-)

标签: c# json azure-language-understanding


【解决方案1】:

我可能错过了您的意图,但如果您只关心特定值而不是整个 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}");

我相信这就是您要从您的对象中获得特定价值的东西。请注意,动态很有用,但这种方法相当快速和肮脏,可能不适合您的实现。

【讨论】:

  • 感谢您的回复这是我们的意图 - 为 sjao9841@demo.com 创建一个新密码
【解决方案2】:

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 by 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 这样您就可以更改类型名称和其他选项。

【讨论】:

    猜你喜欢
    • 2018-09-27
    • 2021-08-22
    • 2016-11-19
    • 2021-07-18
    • 1970-01-01
    • 1970-01-01
    • 2014-10-15
    • 1970-01-01
    • 2020-10-20
    相关资源
    最近更新 更多