1

I'm writing a WebApi that returns an object MyObject. The MyObject class is defined in another DLL which i cannot modify it's source. This MyObject class did not put setters/getters so the public members are not properties, they are just fields.

So in my WebApi code, i want to return this Json MyObject, but all i am getting in the http request is an empty {} json data, when i know for a fact the object does contain data. The only difference is it did not pub setters/getters, that why it is returning {} noting.

How can i return the MyObject back as Json with data without having to make my own MyOwnObject which all the exact fields but property set them as get/set properties?

For Example, if i use

public class MyObject
{
    public string name;
}

this version returns empty {} data even if name contains something, where as

public class MyObject
{
    public string name { get; set; }
}

will property return the Json data, but i am unable to modify MyObject because it is written from another DLL, which i dont have source.

Many thanks.

Tim
  • 133
  • 1
  • 13
  • I'm not sure I understand but can you not just create an object which has the same fields(with `JsonProperty`) as the api and deserialize the JSON into it? – JamesS Jan 03 '20 at 10:20
  • yes, i know i can create an object with all the exact same fields, but that class is VERY big with many many fields.i dont want to duplicate the class. i know i can copy field by field, but is there s simple straightforward way to do it? – Tim Jan 03 '20 at 10:23
  • 1
    Can you inherit the class and implement properties and assign values for parent class fields? – Rajesh G Jan 03 '20 at 10:29
  • let me try it, thanks – Tim Jan 03 '20 at 10:39

2 Answers2

0

You can use Newtonsoft Json.Net (Open source, MIT licence), it will serialize public properties into a stringified JSON object. All you have to do is use the JsonConvert.SerializeObject static method.

However you'd have to do some extra work on your action, since you need to explicitly return a stringified object.

public HttpResponseMessage Get()
{
    // initialize your MyObject instance
    var cls = new MyObject
    {
        name = "AAAAA"
    };

    var stringified = JsonConvert.SerializeObject(cls);
    var response = Request.CreateResponse(HttpStatusCode.OK);

    // explicitly return a stringified JSON object
    response.Content = new StringContent(stringified, Encoding.UTF8, "application/json");
    return response;
}

More on this SO question

0

Don't expose that external object directly through your webapi.

  • keep all your models closer to your API code, where you can change when ever you need. (in your case, you need to create new class in your api project with same properties and gets and sets)
  • use automapper to map external object into your api model (it will make easier for you)
Hiran
  • 1,102
  • 11
  • 18