locked
JSON string as input/output for ASP.NET Web API with Cosmos DB RRS feed

Answers

  • User61956409 posted

    Hi Anandam,

    Anandam

    1) The input would be JSON string. How to store it into the Cosmos DB without deserialization?

    To achieve the above requirement, please refer to the following code snippet.

    using (var stream = new MemoryStream())
    {
        var writer = new StreamWriter(stream);
        writer.Write("{JSON_string_here}");
        writer.Flush();
        stream.Position = 0;
    
        ResponseMessage response = await this.container.CreateItemStreamAsync(stream, new PartitionKey("{PK_here}"));
    
        if (!response.IsSuccessStatusCode)
        {
            //Handle and log exception
        }
        else
        {
            //code logic here
        }
    };

    For more information about Container.CreateItemStreamAsync method, please check https://docs.microsoft.com/en-us/dotnet/api/microsoft.azure.cosmos.container.createitemstreamasync?view=azure-dotnet

    Anandam

    2) For the SQL queries the output would be JSON string. How to return API response as JSON string from the Cosmos DB?

    You can refer to following simple sample to return matched item to client.

    [HttpGet]
    public async Task<IActionResult> GetAsync(string id,string pk)
    {
        Family familyinfo = await this.container.ReadItemAsync<Family>(id, new PartitionKey(pk));
    
        //code logic here
    
        return Ok(familyinfo);
    }

    With Regards,

    Fei Han

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, October 22, 2019 3:11 AM

All replies

  • User61956409 posted

    Hi Anandam,

    Anandam

    1) The input would be JSON string. How to store it into the Cosmos DB without deserialization?

    To achieve the above requirement, please refer to the following code snippet.

    using (var stream = new MemoryStream())
    {
        var writer = new StreamWriter(stream);
        writer.Write("{JSON_string_here}");
        writer.Flush();
        stream.Position = 0;
    
        ResponseMessage response = await this.container.CreateItemStreamAsync(stream, new PartitionKey("{PK_here}"));
    
        if (!response.IsSuccessStatusCode)
        {
            //Handle and log exception
        }
        else
        {
            //code logic here
        }
    };

    For more information about Container.CreateItemStreamAsync method, please check https://docs.microsoft.com/en-us/dotnet/api/microsoft.azure.cosmos.container.createitemstreamasync?view=azure-dotnet

    Anandam

    2) For the SQL queries the output would be JSON string. How to return API response as JSON string from the Cosmos DB?

    You can refer to following simple sample to return matched item to client.

    [HttpGet]
    public async Task<IActionResult> GetAsync(string id,string pk)
    {
        Family familyinfo = await this.container.ReadItemAsync<Family>(id, new PartitionKey(pk));
    
        //code logic here
    
        return Ok(familyinfo);
    }

    With Regards,

    Fei Han

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, October 22, 2019 3:11 AM
  • User1403617900 posted

    Hi Fei Han.

    Thanks for that reply.

    I tried your suggestion as below:

    string sampleJSON = "{ 'id': 'Johnson.16', 'LastName': 'Johnson', 'Parents': [ { 'FamilyName': null, 'FirstName': 'Thomas' }, { 'FamilyName': null, 'FirstName': 'Mary Kay' } ], 'Children': [ { 'FamilyName': null, 'FirstName': 'Henriette Thaulow', 'Gender': 'female', 'Grade': 5, 'Pets': [ { 'GivenName': 'Fluffy' } ] } ], 'Address': { 'State': 'WA', 'County': 'King', 'City': 'Seattle' } , 'IsRegistered' : true }";
    using (var stream = new MemoryStream())
    {
    var writer = new StreamWriter(stream);
    writer.Write(sampleJSON);
    writer.Flush();
    stream.Position = 0;

    PartitionKey pk = new PartitionKey("/LastName");

    ResponseMessage response = await this.container.CreateItemStreamAsync(stream, pk);

    if (!response.IsSuccessStatusCode)
    {
    //Handle and log exception
    Console.WriteLine("\t{0}\n", response.ErrorMessage);
    }
    else
    {
    //code logic here
    Console.WriteLine("\tSuccess\n");
    }
    };

    But got below error:

    "The request payload is invalid. Ensure to provide a valid request payload."

    Tuesday, October 22, 2019 10:23 AM
  • User61956409 posted

    Hi Anandam,

    The request payload is invalid. Ensure to provide a valid request payload.

    To fix above error, please try to modify the code like below.

    using (var stream = new MemoryStream())
    {
        var writer = new StreamWriter(stream);
        string sampleJSON = "{ 'id': 'Johnson.16', 'LastName': 'Johnson', 'Parents': [ { 'FamilyName': null, 'FirstName': 'Thomas' }, { 'FamilyName': null, 'FirstName': 'Mary Kay' } ], 'Children': [ { 'FamilyName': null, 'FirstName': 'Henriette Thaulow', 'Gender': 'female', 'Grade': 5, 'Pets': [ { 'GivenName': 'Fluffy' } ] } ], 'Address': { 'State': 'WA', 'County': 'King', 'City': 'Seattle' } , 'IsRegistered' : true }"; ;
        sampleJSON = sampleJSON.Replace("'", "\"");
           
        writer.Write(sampleJSON);
        writer.Flush();
        stream.Position = 0;
    
        PartitionKey pk = new PartitionKey("Johnson");
    
        ResponseMessage response = await this.container.CreateItemStreamAsync(stream, pk);
    
        if (!response.IsSuccessStatusCode)
        {
            //Handle and log exception
        }
        else
        {
            //code logic here
        }
    };

    And please note that the partition key would be PartitionKey("Johnson") instead of PartitionKey("/LastName").

    With Regards,

    Fei Han

    Wednesday, October 23, 2019 1:12 AM
  • User1403617900 posted

    It worked.
    Thanks Fei Han! :)

    Wednesday, October 23, 2019 6:22 AM