0

I made this Web API Apllication Using ASP.NET und C#

and output response from this API is Json object To can in java script Application Call this API with Ajax

this is C# Code :

 public string Get()
        {

            string Sql3 = "(SELECT top 10 Raspberry_ID, Raspberry_name, Speaker_Name, currently_playing_song,Speaker_Volume,Speaker_Availability, Speaker_Mute,Date_Time,Speaker_Status, Row_Number() over (order by Date_Time desc) as RowNumber FROM Raspi_speaker)T";
            string Sql2 = "Speaker_Volume, Speaker_Status, Speaker_Availability, Speaker_Mute, Date_Time, RowNumber FROM";
            string Sql = "SELECT top 10 Raspberry_ID, Raspberry_name, Speaker_Name, currently_playing_song," + Sql2 + Sql3;
            SqlDataAdapter adap = new SqlDataAdapter(Sql, conn);
            string[] Result = new string[10];
            DataTable dataTable = new DataTable();

            adap.Fill(dataTable);

            int i = 0;

            foreach (DataRow dataR in dataTable.Rows)
            {
                string Val;
                Val = Convert.ToString(dataR["Raspberry_name"]);
                Result[i] = Val;
                i++;
            }

             Object[]  obj = {
        new { RasspiName = Result}
       
    };
         

            if (dataTable.Rows.Count > 0)
            {
                return  JsonConvert.SerializeObject(obj);
            }

            return  "No Data Found";
            

        }


    }

and output is this Json Object:

[{"RasspiName":["Crea_RASPI SONOS","Crea_RASPI SONOS","Crea_RASPI SONOS","Crea_RASPI SONOS","Trais-Sonos-Pi","Trais-Sonos-Pi","Crea_RASPI SONOS","Crea_RASPI SONOS","Crea_RASPI SONOS","Crea_RASPI SONOS"]}]

JavaScript Code is:

function Ajax(){

    var request = new XMLHttpRequest();

    
    request.onreadystatechange = function(){
      
      if(request.readyState == 4 && (request.status == 200)) {
        
        
       var DataR = [];
       
       DataR =JSON.parse(request.responseText) 
  
         console.log(DataR)
       
     }            

}

var url = 'http://localhost:41839/api/Musik';
  request.open('GET',url ,true);
  request.send()



}

My problem is that it treats the Json object as text Although I used ((JSON.parse)) Method in Java Script ... For example when I write (( console.log(DataR[ 0 ])) I get only one Letter for Example [ Instead of Value when I write (( console.log(DataR[ 0 ].RasspiName)) I get Undefined

I dont know if proplem from C# code oder From Java Script

I hope your help thanks so much

Mohamad Eibo
  • 5
  • 1
  • 6
  • There is no `DataR[1]`. Array indexing starts at zero, so you want `DataR[0]`. https://jsfiddle.net/5v8gqcap/ However `DataR[1]` shouldn't yield a letter. The only thing I can think of is that you're converting the object to JSON twice, meaning the JSON text is again converted to JSON and ends up a masked string. Parsing this one will yield a JSON string which would have to be parsed again. –  Feb 22 '22 at 10:36
  • I know that that was only For example – Mohamad Eibo Feb 22 '22 at 10:39
  • Example code demonstrating the problem: https://jsfiddle.net/4s0dyx89/ If your C# code is stringifying twice, try `return obj;` in your controller. –  Feb 22 '22 at 10:42
  • that not woking because Obj is object und Method return only String – Mohamad Eibo Feb 22 '22 at 11:41
  • I can't see the rest of your code, but based on the information in your question, the string returned by your Get() method is json stringified *again*, which is what causes the problem. Did you look at my second fiddle and understand what's happening? You say DataR[0] is `[` which is exactly what happens if you encode an array as JSON *twice* instead of just *once*. –  Feb 22 '22 at 11:47

1 Answers1

0

I don't understand how you defined the API Get method in the back-end code example, but I think you should set something like this:

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json, UseHttpGet = true)]
public string GetDashboardInfo()
{
    //your code here
}

You can use Ajax to make the GET request:

function GetData() {
    try {
        $.ajax({
                type: "GET",
                contentType: "application/json; charset=utf-8",
                url: "http://localhost:41839/api/Musik",
                data: '',
                dataType: "json",
                success: OnSuccessGetData,
                error: OnErrorGetData
         });
    }
    catch (ex) {
         console.log("GetData(): " + ex.toString());
    }
}

function OnSuccessGetData(result) {
    try {
        if (result.d !== "" && result.d !== null) {                   
            var dataSourceJson = JSON.parse(result.d);                   
        }
        else {
            console.log("OnSuccessGetData: result is null!");
        }
    }
    catch (ex) {
        console.log("OnSuccessGetData(): " + ex.toString());
    }
}
    
function OnErrorGetData(httpRequest, textStatus, errorThrown) {
    try {
        console.log("OnErrorGetDashboardData: " + textStatus + " " + errorThrown + " " + httpRequest);
    }
    catch (ex) {
        console.log("OnErrorGetDashboardData(): " + ex.toString());
    }
}  

More about JavaScript Get request here.

dobre.b
  • 64
  • 1
  • 9
  • Granted, OP's title is misleading, but the question is about malformed JSON, not so much about requesting it. Also, OP isn't using jQuery. They should use fetch() instead. –  Feb 22 '22 at 11:02