【问题标题】:Json integer turns string when posting Data .Net Core + React发布Data .Net Core + React时Json整数变成字符串
【发布时间】:2020-09-16 11:28:56
【问题描述】:

我正在尝试将 Car 对象添加到我的数据库中,仅使用字符串就可以正常工作,但是当我尝试添加整数值时,该值在 Json 中被引用,因此变成了字符串。 这是我的 .Net Core 模型:

public class Car : Service
    {
        public string Description { get; set; }
        public int Price { get; set; }
        public string Options { get; set; }
    }

这是我的创建处理程序

 public async Task<Unit> Handle(Command request, CancellationToken cancellationToken)
            {
                var car = new Car
                {
                    id = request.id,
                    Name = request.Name,
                    Description = request.Description,
                    Price = request.Price,
                    Options = request.Options
                };

                _context.Cars.Add(car);
                var success= await _context.SaveChangesAsync() > 0;

                if(success) return Unit.Value;

                throw new System.Exception("Problem saving changes");
            }

create 处理程序同样适用于字符串,但是当我尝试发送整数值时,这是发送的 Json

{id: "f8aa6881-8a90-4510-9505-5471c1f9a656", name: "Mercedes AMG", description: "a", price: "800",…}
description: "a"
id: "f8aa6881-8a90-4510-9505-5471c1f9a656"
name: "Mercedes AMG"
options: "a"
price: "800" //This is the value creating the problem
price:{}; The JSON value could not be converted to System.Int32

请问我如何确保该值作为整数传递?感谢您的帮助。

【问题讨论】:

    标签: .net json reactjs string api


    【解决方案1】:

    今天发现自己遇到了这个问题!

    您可以使用valueAsNumber 来获取双精度值

    double返回元素的值,按顺序解释为下列之一:

    • 时间价值
    • 一个数字
    • NaN如果无法转换

    来源 - MSN Web Docs

    如果您使用基本的“onChange”类型函数来处理输入,您可以将其更改为类似(如果它不是数字,它将像正常一样将其分配为字符串):

        onChange = e => this.setState({ [e.target.name]: e.target.valueAsNumber || e.target.value })
    

    或者如果您需要对转换进行更有限的控制,您可以执行类似于@bennygenelhis answer 中建议的操作:

    this.setState({
      [e.target.name]: e.target.type === 'number' ? parseInt(e.target.value) : e.target.value
    });
    
    // or
    
    this.setState({
      [e.target.name]: e.target.name === 'price' ? parseFloat(e.target.value) : e.target.value
    });
    

    希望这会有所帮助!

    【讨论】:

      猜你喜欢
      • 2018-09-20
      • 2022-01-18
      • 1970-01-01
      • 2020-11-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多