2017-02-20 10 views
1

http://localhost:62633/returnsdesk からGETに応答してjsonリストを返すWCF Web API(.Net 4.5)を作成しました。WCFが返すjsonリストにもリストの名前が必要

[{ "名前": "ステータス" を "拒否": "FULL"}、{ "名前"、 "戻る"、 "ステータス": "OK"}]

しかし

{ "宛先": [{ "のDestinationNameは": "拒否"、 "ステータス": "FULL"}、{ "のDestinationName": "StevesDesk"、」より良いJSONのように見えるフォーマットしますステータス]:[OK]}] }

私はこれをどのようにgoogleするのか分かりません。

WebGetにWCFを取得するには& WebMessageFormat.Jsonにjsonリストの名前を付けますか?

+1

タイトルはあなたの質問にどのように関連していますか? – wkl

+0

あなたは質問の名前について正しいです。私は今それを修正するつもりです。それがどこから来たのか分からない。ありがとう。 – Steve

+1

@Will No.編集されていません。 WCFが返す文字列です。{{"Name": "reject"、 "status": "FULL"}、{"Name": "returns"、 "status": "OK"}]バイト単位。問題は、リストの名前が含まれていないということです。 – Steve

答えて

0

これは本当に@ user18925に属します

:今WCFが所望の名前を返す

[DataContract] 
    public class retDesks { [DataMember] public List<Desk> destinations; } 

:38

のようなシリアル化され、リストにWCFによって返されたタイプ(List<Desk>)を取り、別のタイプのそれを包みます

{"destinations": [{"ID": "destinationName": "拒否"、 "ステータス": "完全"}、{"ID":2、 "destinationName": "StevesDesk"、 "status ":" OK "}]}

しかし、Json Deskオブジェクトにも属性IDが含まれていることに気づくでしょう。 ID[DataMember]で飾られていなかったので、IDDeskの定義によって出力から隠される前に。

ただし、Deskの装飾は、retDesks[DataMember] List<Desk>の場合、Deskタイプ全体が公開されているので問題にはなりません。

どうすれば対処できますか? ほとんどのようList<Desks>の性質をフィルタリングするためのLINQを使用し、迅速な提案を愛して:ここ

var d1 = _desks.Select(e => new { e.destinationName, e.status }); 

悪いニュースはd1ある匿名型のリストです。 これは、List<Desks>を含むretDesksタイプの定義には受け入れられません。

第3のタイプpublic deskRet [ public string destinationName; public string status; }を作成し、このタイプをLinqの出力と返されるタイプretDesksのインスタンスの間のリストとして設定します。

{ "目的地":[{ "のDestinationNameは": "拒否"、 "ステータス": "FULL"}あなたはspec'ed出力を持って一日の終わりに

public class Desk { public int ID; public string destinationName; public string status; } 

public class retDesks { [DataMember] public List<deskRet> destinations; } 

public class deskRet { public string destinationName; public string status; } 

... 

List<deskRet> d1 = _desks.Select(e => 
    new deskRet{ destinationName=e.destinationName, status=e.status } 
    ).ToList<deskRet>(); // maybe I'm working to hard to guarantee the type. But I'm okay with that 
return(new retDesks{ destinations=d1 }; 

、{ "のDestinationName": "StevesDesk"、 "ステータス": "OK"}]}

しかし、次回はJson.NETのようなサードパーティの枠組みを検討します。または、おそらく、.Net WCFフレームワークを使用するカスタムJson Serialzerのみ。

2

私はあなたが

[WebInvoke(Method = "GET", 
     RequestFormat = WebMessageFormat.Json, 
     ResponseFormat = WebMessageFormat.Json, 
     UriTemplate = "returnsDesk")] 
[WebGet(ResponseFormat = WebMessageFormat.Json)] 

List<Desk>を返す飾ら方法を、持っていると仮定します。

public List<Desk> GetDesks() 
{ 

はあなたではなく、そのようなリストを含む、List<Desk>として定義[DataMember]飾らdestinations財産、と新しいクラスDeskListを返却する必要があります。 LongNameContractResolverため

+0

あなたの前提はすべて正しいです。これはGETです。私は '\t \t [返信:MessageParameter(Name =" balbal ")]'装飾を試してみました(この属性はプログラマチックにカスタマイズすることができます)。あなたが言っていることの残りの部分は意味をなさないので、後でそれを試してみて、ここに戻ってきます。どういうわけか、ちょうど私がちょうどそれがちょうどリストののために起こったと思っていて、それがそうでなかったのを見て驚いた。 – Steve

+1

@ user1892539チャームのように働いたが、たぶんあなたのためのヒントを持っています。私の内部クラス 'Desk'には、前にjsonに公開されていなかった属性が[DataMember]デコレーションを持たないことによってあります。もちろん、 'Desk'クラス自体にはまだ[destinationName]と[status]が[DataMember]で装飾されていても、これらの属性はすべてjson出力に含まれています。私は正直言って、この1つが来るのを見ていませんでした。 – Steve

+0

あなたはこの[質問](http://stackoverflow.com/questions/27092802/serialize-object-into-json-but-only-include-properties-with-the-datamember-att)を求めているようですね、arenあなたは? –

0

クレジットは、あなたがNewtonSoftを使用することができますBryon Rogers

Hiに行きます。JSONシリアライズするための基準とデシリアライズは


これは次の出力(JSON文字列) enter image description hereを生成

using Newtonsoft.Json; 
using Newtonsoft.Json.Serialization; 
using System; 
using System.Collections.Generic; 

namespace JsonNamedList 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      //Destinations object 
      var destinations = MockGetDestinations(); 
      //Destinations object as Json string, use the LongNameContractResolver to ignore the Json Property Name 
      var strDestinationsJson = LongNameContractResolver.Serialize(destinations, true); 
      //Print the destinations Json to output 
      Console.WriteLine(strDestinationsJson); 
      //Stop closing the console window 
      Console.ReadKey(); 
     } 

     static Destinations MockGetDestinations() 
     { 
      //[{"Name":"reject","status":"FULL"},{"Name":"returns","status":"OK"}] 
      var apiResponse = "[{'Name':'reject','status':'FULL'},{ 'Name':'returns','status':'OK'}]".Replace("'", "\""); 
      var wrappedApiResponse = WrapIntoDestinations(apiResponse); 
      //destinations as object 
      var destinations = JsonConvert.DeserializeObject<Destinations>(wrappedApiResponse); 

      return destinations; 
     } 

     static string WrapIntoDestinations(string apiResponse) => $"{{'destinations': {apiResponse} }}".Replace("'", "\""); 
    } 

    public class Destination 
    { 
     [JsonProperty(PropertyName = "Name")] 
     public string destinationName { get; set; } 

     [JsonProperty(PropertyName = "status")] 
     public string status { get; set; } 
    } 
    public class Destinations 
    { 
     [JsonProperty(PropertyName = "destinations")] 
     public IEnumerable<Destination> destinations { get; set; } 
    } 
    public class LongNameContractResolver : DefaultContractResolver 
    { 
     protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization) 
     { 
      // Let the base class create all the JsonProperties 
      // using the short names 
      IList<JsonProperty> list = base.CreateProperties(type, memberSerialization); 

      // Now inspect each property and replace the 
      // short name with the real property name 
      foreach (JsonProperty prop in list) 
      { 
       prop.PropertyName = prop.UnderlyingName; 
      } 

      return list; 
     } 
     public static string Serialize(object obj, bool useLongNames) 
     { 
      JsonSerializerSettings settings = new JsonSerializerSettings(); 
      settings.Formatting = Formatting.Indented; 
      if (useLongNames) 
      { 
       settings.ContractResolver = new LongNameContractResolver(); 
      } 

      return JsonConvert.SerializeObject(obj, settings); 
     } 
    } 
} 

あなたの質問に答えるために以下のコードを見てみましょうオブジェクト

関連する問題