Include NULL Values in JSON on a specific request

Is there a way to only include json null values for a specific dto request?

In order for VueJS to be reactive (and here), the props need to exist.

I only want to do this for a couple requests, so I do not want to use the global:

JsConfig.IncludeNullValues = true;

Is there a way to do this only for a specific request? Possibly an attribute on the request?

// pseudo code
public class MyService : Service {
  [JsConfig.IncludeNullValues]
  public async Task<ResponseDto> Get(RequestDto request) {
    // do something
    return new ResponseDto();
  }
}

So found this…
If this is how to do it… I don’t like how it would be hidden in AppHost. It’s not as clear/explicit as an attribute would be that a request would include NULLs.

But if that is the only way then that is how it shall be.

JsConfig<Dto>.RawSerializeFn = (obj) =>
{
    using (JsConfig.With(includeNullValues: true))
    {
        return obj.ToJson();
    }
};

JsConfig<Dto>.RawDeserializeFn = (json) =>
{
    using (JsConfig.With(includeNullValues: true))
    {
        return JsonSerializer.DeserializeFromString<Dto>(json);
    }
};

Source: Response DTOS doesnt show properties with null value

Note: JsConfig.With() has been marked as Obsolete.

JsConfig.With(includeNullValues: true)

instead use

JsConfig.With(new Config() { IncludeNullValues = true })

Does anyone foresee any issues with declaring the JsConfig<Dto>.RawSerializeFn inside a static constructor of a service?

That way I can keep it more visible/explicit that request includes nulls?

// pseudo code
public class MyService : Service {

  static MyService() {
    JsConfig<ResponseDto>.RawSerializeFn = (obj) =>  {
      using (JsConfig.With(new Config() { IncludeNullValues = true }) {
        return obj.ToJson();
      }
    };
  }

  public async Task<ResponseDto> Get(RequestDto request) {
    // do something
    return new ResponseDto();
  }
}

Put all your initialization/start up logic with the rest of your configuration where it belongs, in your AppHost. Doesn’t make sense to scatter it across static constructors which you can’t control when exactly it’s run.

The Customize JSON Responses in your Service docs show how you can customize the JSON per Service by returning a HttpResult with a ResultScope or by returning the serialized JSON string.

Alternatively you can customize the JSON on-the-fly on the querystring, e.g:

/route?jsconfig=inv
1 Like

I like the querystring option the best. Thanks! That is much cleaner.