logo
down
shadow

How to convert API Json response to C# Array?


How to convert API Json response to C# Array?

By : loading
Date : January 11 2021, 05:14 PM
This might help you Wow, if you can request the API to respond with json or xml you can make short work of this - but if it really is just tabular text then life becomes a bit more complicated as you need to manually parse the data and convert it into objects.
Let's consider an example object that you might target, containing a collection of another custom type. (Have used list for convenience as we may not know the length of the expected data, you can substitute this for a HashSet if preferred, or even swap things around a bit make this a private collection with a public method that returns it as an array if array is what you need to make use of etc. Also you can change the member types as needed).
code :
public class ApiData
{
    public decimal Latitude { get; set; }
    public decimal Longitude { get; set; }
    public string RadiationDatabase { get; set; }
    public List<ApiSlopeAngle> OptimalSlopeAngle { get; set; }

    public ApiData()
    {
        OptimalSlopeAngle = new List<ApiSlopeAngle>();
    }
}
public class ApiSlopeAngle
{
    public int Year { get; set; }
    public string Month { get; set; }
    public decimal Hh { get; set; }
    public ApiSlopeAngle(int year, string month, decimal hh)
    {
        Year = year;
        Month = month;
        Hh = hh;
    }
}
// Sample data
string apiStringData = "Latitude (decimal degrees):\t45.000\r\nLongitude (decimal degrees):\t8.000\r\nRadiation database:\tPVGIS-CMSAF\r\nOptimal slope angle (deg.):\t\r\n\r\nYear\t\t Month\t\tHh\r\n2005\t\tJan\t\t56.5\r\n2005\t\tFeb\t\t75.7\r\n2005\t\tMar\t\t118\r\n2005\t\tApr\t\t131\r\n2005\t\tMay\t\t193\r\n2005\t\tJun\t\t211\r\n2005\t\tJul\t\t217\r\n2005\t\tAug\t\t179\r\n2005\t\tSep\t\t115\r\n2005\t\tOct\t\t72.9\r\n2005\t\tNov\t\t42.4\r\nHh: Irradiation on horizontal plane(kWh/ m2)\r\n\r\nPVGIS(c) European Communities, 2001 - 2016";
// Define the regex patterns to use
string lattPattern = "(Latitude\\s\\(decimal\\sdegrees\\):)(\\t\\d+\\.*\\d*)";
string longPattern = "(Longitude\\s\\(decimal\\sdegrees\\):)(\\t\\d+\\.*\\d*)";
string radDbPattern = "(Radiation\\sdatabase\\:)(\\t)(PVGIS\\-CMSAF)";
string osaPattern = "((19|20)\\d{2})(\\t\\t)([A-Z]+[a-z]*)(\\t\\t\\d+\\.*\\d*)";

// Create the matches for the top-level data
var lattitude = Regex.Match(apiStringData, lattPattern);
var longitude = Regex.Match(apiStringData, longPattern);
var radDb = Regex.Match(apiStringData, radDbPattern);

// Create the result object, and populate the top-level properties
ApiData apiObject = new ApiData();
apiObject.Latitude = Convert.ToDecimal(lattitude.Groups[2].ToString());
apiObject.Longitude = Convert.ToDecimal(longitude.Groups[2].ToString());
apiObject.RadiationDatabase = radDb.Groups[3].ToString();

// Split the sample data into an array 
// to make it easier to enumerate what will become the nested data
string[] apiArray = Regex.Split(apiStringData, "\r\n");

// Step through it
foreach (string s in apiArray)
{
    var angle = Regex.Match(s, osaPattern, RegexOptions.IgnoreCase);
    if (angle.Success == true)
    {
        // Create the properties
        int year = Convert.ToInt32(angle.Groups[1].ToString());
        string month = angle.Groups[4].ToString();
        decimal hh = Convert.ToDecimal(angle.Groups[5].ToString());

        // Add to the collection
        ApiSlopeAngle apiDate = new ApiSlopeAngle(year, month, hh);
        apiObject.OptimalSlopeAngle.Add(apiDate);
    }
}


Share : facebook icon twitter icon
How to convert JSON response to PHP array

How to convert JSON response to PHP array


By : user7730997
Date : March 29 2020, 07:55 AM
will be helpful for those in need I'm trying to convert this response into a PHP array: , Why not just the json_decode() function.
code :
$array = json_decode($input);
Convert a JSON Response into an Array of Objects

Convert a JSON Response into an Array of Objects


By : user2391840
Date : March 29 2020, 07:55 AM
may help you . Looks like you just need the values of the dictionary, however, you need to not only access the data of the response, but the 'data' of the actual response data itself.
code :
const data = Object.values(response.data['data']);
How to convert JSON Response to String Array

How to convert JSON Response to String Array


By : Teri Zinkerbaby
Date : March 29 2020, 07:55 AM
I hope this helps . Paste your json string to this website, and generate your pojo. Use the Gson to parse your string and bind to generated pojo.
Convert json string response representing UCHAR array to Byte array

Convert json string response representing UCHAR array to Byte array


By : user3098630
Date : January 11 2021, 02:18 PM
it helps some times Turns out that, although the output of the API function is UCHAR, when it comes in as part of the JSON string, it is a base64 string, so this works for me:
code :
byte[] pdfBytes = Convert.FromBase64String(pdfObj.result);
How do you convert specific array values in a JSON response to be just the first value in the array?

How do you convert specific array values in a JSON response to be just the first value in the array?


By : Ahmed Abuelmagd
Date : September 21 2020, 04:00 PM
With these it helps You can do this with a custom Unmarshal as described here:
http://choly.ca/post/go-json-marshalling/
code :
func (u *User) UnmarshalJSON(data []byte) error {
    type Alias User
    aux := &struct {
        Settings []*Settings `json:"settings"`
        *Alias
    }{
        Alias: (*Alias)(u),
    }
    if err := json.Unmarshal(data, &aux); err != nil {
        return err
    }
    u.Settings = aux.Settings[0]
    return nil
}
Related Posts Related Posts :
  • Passing enum type to Converter with integer value
  • Pool of objects with objects that are already on the scene in advance
  • StatusBar text fade-out when binding using Caliburn.Micro
  • Queryfilter on ApplicationUser in OnModelCreating in ApplicationDbContext creates StackOverflowException
  • How to get record form a different table based on a value from first table with linq expression?
  • Show data in Grid from returned model
  • Using Attributes to Override Data Model Conventions
  • Basic OOP console calculator, result Error
  • Compositon and Repository pattern
  • Multiple using statements with if condition
  • How do i increase a number by 1 in every line that contain the number 1
  • Add binding to elements that are created in codebehind
  • How to add a column in an existing AspNetUsers table
  • Order a list of elements with another list of doubles
  • How to setup a NuGet package to copy content files to output build directory?
  • In SignalR Core using ChannelWriter: Do I need to call TryComplete twice if there's an exception?
  • C# GetProcessesByName: issue with colon
  • c# wpf | create complex object with user-defined name to Serialize into JSON
  • How can I get a instance of a generic list with reflection?
  • WPF XAML - Design time and visibility of textbox
  • EF Core and MySql query is too slow
  • Getting Registered App Display Name from an App Id
  • How to get all variables from a string
  • Delete entity with all childs connected
  • Azure Build agent cant´t find class library referance
  • Initialize Nested Dictionaries in c#
  • .Net Core Binding
  • Loading a pop up page in ASP.net through a js file
  • How to pass alert or notification message from controller to View?
  • C# to pause, turn on ssas server, backup cube.... how to?
  • How to execute DataTable.Select() for a column of custom class type for a particular element in that C#
  • how to connect mysql8.0 with C#
  • Passing incorrect values into MultiValueConverter by MultiBinding
  • Can i use IEnumerator as Update func?
  • Blazor Textfield Oninput User Typing Delay
  • Performing both layout and render transform results in wrong output
  • uwp beforetextchanged cursor moving in front of text
  • How to keep duplicates from a string[] exclude words from a List and print them out
  • .Net Core Strings.Asc/Mid/Chr/Len missing even after importing Microsoft.VisualBasic
  • How to return to previous search page without being asked to Confirm Form Re-submission and keeping the results on ASP.N
  • How set a identity scaffolding item/page how initial page in asp.net MVC core?
  • LINQ isn't calling Dispose on my IEnumerator when using Union and Select, expected behavior or bug?
  • What is "ByteArray.uncompress()" in AS3 equivalent to in C#?
  • Getting a specific letter from a string variable for my simple guessing game for clues
  • Send an email with Outlook without a subject --- dialog box issue
  • passing List<MyModel> from my controller in the "WebInterfaceProject" to the processor method in "D
  • How to convert Word document created from template by OpenXML into MemoryStream?
  • How can I make a single slider that changes the color of an object?
  • Remap JSON parameter in c#
  • What is the difference between "this ref" and "ref this" when talking about C# 7.2 ref extension met
  • Convert OpenSSL encryption into native C#
  • Accessing Properties in Razor Pages
  • How to get SOAP element value
  • Projection after Group
  • C# error cannot convert sytem.text.regularexpressions.match to string
  • Issues with Save/Load System in a Text Based Adventure game made with ScriptableObjects in Unity
  • VS2019 MSBuild.exe - ASP .Net MVC project fails to publish when using PublishProfile, but works when using OutDir parame
  • Does <pages validateRequest="false" /> in Web.config still matter?
  • How to send new request to redirect URL with new access token
  • Attempt to invoke virtual method on a null object reference Xamarin LockScreen
  • shadow
    Privacy Policy - Terms - Contact Us © festivalmusicasacra.org