0

I can't seem to find anything in the OpenRasta docs or tutorials that shows how to use arbitrary JSON objects (i.e. objects not predefined using C# classes) for both receiving from and responding back to the client.

One way to do it would be to use JsonValue and write a custom codec that would just use the (de)serialization features provided by JsonValue. That should be pretty straightforward and less than 50 lines of code, but I wondered if there isn't anything built into OpenRasta?

(One downside of JsonValue is that MS has not yet released it, so you can't yet deploy it to customers (see 1. "Additional Use Rights"). But in cases where that matters, any other Json library, like Json.NET can be used.)

4

2 に答える 2

0

ほとんどの人と同じように、json.net を使用してハンドラーへの入力および出力としてダイナミクスをサポートする非常に単純なコーデックを作成しました。そのコーデックを匿名タイプで登録することもでき、見事に機能します。あなたはこれで終わります:

public object Post(dynamic myCustomer) {
  return new { response = myCustomer.Id };
}
于 2011-09-15T11:30:59.490 に答える
0

JsonFx を使用して JSON コーデックを実装しました。こんなふうになります:

using System.IO;
using System.Text;
using JsonFx.Json;


namespace Example
{
  [global::OpenRasta.Codecs.MediaType("application/json")]
  public class JsonFXCodec : global::OpenRasta.Codecs.IMediaTypeWriter, global::OpenRasta.Codecs.IMediaTypeReader
  {
    public void WriteTo(object entity, global::OpenRasta.Web.IHttpEntity response, string[] codecParameters)
    {
      JsonWriter json = new JsonWriter();
      using (TextWriter w = new StreamWriter(response.Stream, Encoding.UTF8))
      {
        json.Write(entity, w);
      }
    }


    public object ReadFrom(global::OpenRasta.Web.IHttpEntity request, global::OpenRasta.TypeSystem.IType destinationType, string destinationName)
    {
      JsonReader json = new JsonReader();
      using (TextReader r = new StreamReader(request.Stream, Encoding.UTF8))
      {
        return json.Read(r, destinationType.StaticType);
      }
    }


    public object Configuration { get; set; }
  }
}

「オブジェクト」に登録されている場合、どのクラスでも機能するようです。

ResourceSpace.Has.ResourcesOfType<object>()
                 .WithoutUri
                 .TranscodedBy<JsonFXCodec>();
于 2012-05-30T11:07:37.017 に答える