1

I am working on asp.net mvc 4 web api. I am trying to return list of records as a json response. my table contains four fields field1,field2,field3 and field4 and i write the action like,

public List<MyTable> GetRecords()
{
return context.mytable.ToList();
}

and i got the response like,

[{"field1":true,"field2":false,"field3":true,"field4":false}]

Now i need to get only the fields whose value true so the above response will be like,

[{"field1":true,"field3":true}]

I have tried with [JsonIgnore] attribute but it con be used only at the time of model class creation like,

[JsonIgnore]
public string field1{get; set;}

How could i programatically apply jsonignore on the fields so that i can able return only specified fields. please guide me.

1 Answer 1

0

Can you make the ignored fields null and the add this to ignore null while serialization :

GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;
3
  • No... I am not handling null values here. i need make condition between true and false values. and i want to make it effect to single action not to the whole project Commented Nov 16, 2012 at 10:50
  • I suggested if you could you make the fields to be ignored as null in the controller. If yes, then with the above setting those fields will be ignored. Programatically adding [JsonIgnore] "might" be possible with reflection but it will not solve the purpose with xml (or some other) serialization
    – Sando
    Commented Nov 16, 2012 at 11:03
  • 1
    Another idea here could be if you could tune your queries to return lesser fields and then use DataReader to 'dynamic' (or DataSet to 'dynamic') conversion and then directly serialize the dynamic object(s) to response stream.
    – Sando
    Commented Nov 16, 2012 at 11:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.