Home > Software engineering >  How to access short URl from Json object in c# - Bitly
How to access short URl from Json object in c# - Bitly

Time:10-22

I am using Bitly api in Asp.net project to create short Url. I am getting result but it is in json format. How do I retrieve short Url from it?

[HttpGet("sendNotification/{PlanId}")]
        [ValidateModelState]
        public async Task<IActionResult> SendNotification()
        {
                var link ="https://chats.landbot.io";
                var shortUrl = await GetShortUrl(link);
              
                return NoContent();
            }
            
        }
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

shortUrl giving me everything as below

{"created_at":"2021-10-21T04:01:53 0000","id":"bit.ly/shortUrl","link":"LongUrl","archived":false,"tags":[],"deeplinks":[],"references":{"group":"https://api-ssl.bitly.com/v4"}}
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

In the above line, id contains the Short link and that's the only link I need. Can anyone tell me what I should do?

CodePudding user response:

Create class like below

public class Item
 {
    public string created_at;
    public string id;
    public string link;
  }

And in your method read json string like below code using newtonsoft json In items you will get the values.

Item items = JsonConvert.DeserializeObject<Item>(json);

CodePudding user response:

1.JObject:

{{"created_at":"2021-10-21T04:01:53 0000","id":"bit.ly/shortUrl","link":"LongUrl","archived":false,"tags":[],"deeplinks":[],"references":{"group":"https://api-ssl.bitly.com/v4"}}}

If you want to get idfrom JObject,you can use:

var id=jObject["id"].Tostring;

2.json string:

{\"created_at\":\"2021-10-21T04:01:53 0000\",\"id\":\"bit.ly/shortUrl\",\"link\":\"LongUrl\",\"archived\":false,\"tags\":[],\"deeplinks\":[],\"references\":{\"group\":\"https://api-ssl.bitly.com/v4\"}}

If you want to get id from json string,you can use:

var id=JObject.Parse(jsonString)["id"].Tostring;
  • Related