1

How can API return customised names?

For example:

<UserInfo>
    <name>aaaaaa</name>
    <endpoints>
        <int>1</int>
        <int>2</int>
    </endpoints>
</UserInfo>

is generated from code

public class UserInfo
{
    public string name;
    public int[] endpoints;
}

I'd like to return this:

<User name="aaaaaa">
    <endpoints>
         <endpoint>1</endpoint>
         <endpoint>2</endpoint>
    </endpoints>
</User>

How can I

  1. Rename UserInfo to User
  2. Define name as attribute
  3. Rename fields in endpoints array to endpoint?

I've tried using [DataContract] and [DataMember], but nothing changed.

EDIT: Method I use to get output:

    // GET api/info
    [HttpGet("info")]
    public IActionResult GetInfo([FromHeader] string auth)
    {
        if (HasAccess(auth, Endpoints.Info))
        {
            return new ObjectResult(Database.GetInfoAboutUser(auth));
        }
        else
        {
            return Unauthorized();
        }
    }
6
  • I answered number 1, I could not understand numbers 2 and 3, therefore I could not help. Commented Apr 23, 2018 at 20:39
  • @MohammedNoureldin Thank you! It would be great if you had idea how to do instead of ... <name>aaaa</name> this <User name="aaaaa">...</User>. 3. means, that items in the array are named int now, I want to change their name. Commented Apr 23, 2018 at 20:44
  • Please post what code you use to generate that XML, and try my answer for number one and three to be sure that we may get rid of it. Commented Apr 23, 2018 at 20:47
  • I use the asp.net core web api - I just return object from controller and asp serializes it on its own. I'll edit answer and add source code tomorrow, as I don't have access to the source code now. learn.microsoft.com/en-us/aspnet/core/tutorials/… Commented Apr 23, 2018 at 21:03
  • OK, then we can try further when you post the code. Commented Apr 23, 2018 at 21:13

1 Answer 1

1

You have 3 questions in one question. However:

Number one:

I guess this is what you want:

[XmlType(TypeName = "User")]
public class UserInfo
{
...
}

Number three:

int[] values = { 1, 2, 17, 8 };

XDocument doc = new XDocument();
doc.Add(new XElement("endpoints", values.Select( x=> new XElement("item", x))));
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.