Skip to content
This repository has been archived by the owner on May 16, 2022. It is now read-only.

[Question]Handle Number field with 'null' value #237

Open
oOtroyOo opened this issue Oct 26, 2020 · 1 comment
Open

[Question]Handle Number field with 'null' value #237

oOtroyOo opened this issue Oct 26, 2020 · 1 comment

Comments

@oOtroyOo
Copy link

For example.
We have some apis like this

{
    "num":1
}

And I have a type contains int num;

But some how,(due to server developing which I'm uncertain), our srever could possible to return value suchas

{
    "num":  null
}

then my client will throw a Exception.
I don't want to change all my types into nullable values , suchas int? num ,
By fix this issue , I changed codes follows:

public struct JsonReader
{
        public long ReadInt64()
        {
            SkipWhiteSpace();

            int readCount;
            var v = NumberConverter.ReadInt64(bytes, offset, out readCount);
            if (readCount == 0)
            {
+            if (nullTokenSegment != ReadStringSegmentUnsafe())
                    throw CreateParsingException("Number Token");
            }

            offset += readCount;
            return v;
        }
}

The purpose is to check the value is null , so i can skip this value by defualt .

Is there a better way to solve the issue ?

@tomsoftware
Copy link

tomsoftware commented Apr 8, 2021

I think the best way is to as Nullable in you c# class (or you can use the ? as shortcut)
and use a proxy getter...

     public class Test
     {
        [IgnoreDataMember]
        public int Num { get; set; }

        [DataMember(Name = "num")]
        public int? RealNum
        {
            get
            {
                return this.Num;
            }

            set
            {
                this.Num = value.GetValueOrDefault();
            }
        }
    }

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants