2

I have a class BasketItem:

public class BasketItem
{
    public long FoodId;
    public int Count;
}

I have a AddToBasket controller which adds items to basket and then returns the json value of BasketItem[]:

I'm using return Json(items); which items is of type BasketItem[].

The returned json is like:

[{"foodId":6,"count":1},{"foodId":5,"count":1},{"foodId":4,"count":1}]

while it Should be like:

[{"FoodId":6,"Count":1},{"FoodId":5,"Count":1},{"FoodId":4,"Count":1}]

How to prevent return Json from renaming the key names?

3
  • 1
    The default behavior in MVC is actually to return pascal-cased JSON since it uses JavaScriptSerializer under the hood unless something is overridden. There's no way to answer your question without additional details. Commented Mar 31, 2017 at 4:01
  • 1
    No, I don't think you do understand. Your returned json is actually camelCased, not PascalCased, which is atypical behavior for MVC. As a result, something in your code is currently overriding the default behavior and there's no way for us to tell you what it is because it is in your codebase. Commented Mar 31, 2017 at 4:07
  • And as an aside, camelCased is the industry preferred standard which is why a developer in your organization most likely set it up this way. Commented Mar 31, 2017 at 4:08

1 Answer 1

1

I solved the problem by using the overload of the Json(object, JsonSerializerSettings):

   var serializerSettings = new JsonSerializerSettings
        {
            ContractResolver = new DefaultContractResolver(),
        };
        return Json(items, serializerSettings);
Sign up to request clarification or add additional context in comments.

Comments

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.