Hi I'm using the below class
Public List<string> name;
Public List<string> midname;
Once I serialize it I'm getting the following output like
{"name":[hari],"midname":null}
But I want my answer to be like this
{"name":[hari]}
It shouldn't display the class attribute that has null value and I'm using c# .net framework.
In our example we have one node "address" with null value and program removes it from generated json. If you run the program you will get following output: Then called gson.toJson (jsonObject) method which removes the null valued nodes from the generated JSON text. Here is the code example:
In almost all cases, Apex doesn't use empty strings, instead returning null. For most remaining cases, you can always use null explicitly: Show activity on this post. suppressApexObjectNulls => Type: Boolean If true, remove null values before serializing the JSON object.
There is a third technique - returning an empty string where there are nulls. This might not be the way most people would do, but this might be a requirement for an upstream API. To do this we create a JsonConverter. This is a special class that we can subclass and override to control the serialization (and deserialization) process of an object.
You can see in the output that the null is output explicitly. Now there are two main ways to handle this - the first is to have the attribute with a value of null, as we have done. The second is not to have the attribute there at all, if its value is null. To achieve the second method we configure our serialization as follows:
The full answer depends on how you're serializing your class.
If you're using data contracts to serialize your classes, set EmitDefaultValue = false
[DataContract]
class MyClass
{
[DataMember(EmitDefaultValue = false)]
public List<string> name;
[DataMember(EmitDefaultValue = false)]
public List<string> midname { get; set; }
}
If you're using Json.Net, try this instead
class MyClass
{
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public List<string> name;
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public List<string> midname { get; set; }
}
Or set it globally with JsonSerializerSettings.NullValueHandling = NullValueHandling.Ignore
If you are using Json.Net
then You can try this by Decorating your property like this
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public List<string> name { get; set; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With