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

问题描述 投票:2回答:2

下面是我的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 [email protected]",
  "topScoringIntent": {
    "intent": "ResetLANIDpassword",
    "score": 0.9956063
  },
  "intents": [
    {
      "intent": "ResetLANIDpassword",
      "score": 0.9956063
    },
    {
      "intent": "None",
      "score": 0.179328963
    }
  ],
  "entities": [
    {
      "entity": "[email protected]",
      "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#获得它?下面是我尝试的代码但没有出现:Message =从JsonReader读取JObject时出错。路径'',第0行,位置0. Source = Newtonsoft.Json

c# json luis
2个回答
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}");

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


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所以你可以改变类型名称和其他选项。

© www.soinside.com 2019 - 2024. All rights reserved.