Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

C#: Option to validate duplicate fields during json deserialization #20288

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

searoz
Copy link

@searoz searoz commented Feb 10, 2025

The issue

Proto:

syntax = "proto3";

package test;

message User {
  string first_name = 1 [json_name = "first_name"];
  string last_name = 2;
}

Code:

using Google.Protobuf;
using Test;

const string json =
    """
    {
        "first_name": "John",
        "first_name": "Alan",
        "last_name": "Doe",
        "lastName": "Smith"
    }
    """;

var user = JsonParser.Default.Parse<User>(json);
Console.WriteLine($"{user.FirstName} {user.LastName}");

Output:

Alan Smith

Why is this a problem?

This is a pretty unexpected behavior. Even using json_name cannot fully prevent one from using duplicate fields in json

What about implementations in other languages?

protobuf-go features a specific check for duplicate fields

What does this PR do?

This PR introduces an optional setting IgnoreDuplicateFields (true by default). If set to false, it makes JsonParser validate duplicate fields. Coming back to out example:

Code:

using Test;

const string json =
    """
    {
        "first_name": "John",
        "first_name": "Alan",
        "last_name": "Doe",
        "lastName": "Smith"
    }
    """;

var user = JsonParser.Default.WithIgnoreDuplicateFields(false).Parse<User>(json);
Console.WriteLine($"{user.FirstName} {user.LastName}");

Output:

Google.Protobuf.InvalidProtocolBufferException: Multiple values specified for field first_name

@searoz searoz requested a review from a team as a code owner February 10, 2025 07:54
@searoz searoz requested review from jskeet and removed request for a team February 10, 2025 07:54
Copy link

google-cla bot commented Feb 10, 2025

Thanks for your pull request! It looks like this may be your first contribution to a Google open source project. Before we can look at your pull request, you'll need to sign a Contributor License Agreement (CLA).

View this failed invocation of the CLA check for more information.

For the most up to date status, view the checks section at the bottom of the pull request.

@shaod2 shaod2 added the c# label Feb 10, 2025
@tonyliaoss
Copy link
Member

Hello @searoz, we can't start reviewing your PR unless the CLA has been signed.

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

Successfully merging this pull request may close these issues.

3 participants