c # — десериализация PHP JSON в C Sharp.

Может ли кто-нибудь помочь мне с моей десериализации моего JSON. Я попытался json2csharp, я получил класс, но когда я пытаюсь его, он продолжает пустым и показывает ошибку.

JSON:

{"data":[{"officeID":"L4UFJw8GpQPg8iryJlHgeQ8L9wvGaGMozF33HxYrouY=","firstName":"R6UELs10\/qC+e9Iej1Sfh44H53bC1iez1FX9UoBdmL4=","lastName":"dZh5xGkYre\/Qjv\/d8PnYE+0F+YB\/pACDsOhnbT1vC7I=","userName":"oJ9SUemStHW6XGJrRSgQJxBUxHIWKejj3yVjbxiNHH8=","birthdate":"386TvajxJiPRXU4UT5OIqH3jmgSqqmv+n09tqxR9458=","email":"1kuUiACYGwkHseT32NfCbb6QH68Mq09ur5LdBo2SzUhdD6mWQjN9leekZrcZVmzcVCfSA4iEgTIspS3j8naYjg==","functionCategoryID":"79kSmrt7HmEYhqBd+NGd8la3NRVkSaeU+9rx7ri\/jG0="},{"officeID":"Ue86sZNLpM0dZXDBbAw4bgpg36te\/Uym3j\/7c\/RK6So=","firstName":"OK6EiNwnB7Ixb25ua62Us1sCMQ3VlGrjAawtU5pamFk=","lastName":"OK6EiNwnB7Ixb25ua62Us1sCMQ3VlGrjAawtU5pamFk=","userName":"OK6EiNwnB7Ixb25ua62Us1sCMQ3VlGrjAawtU5pamFk=","birthdate":"CgQqdhV3+ZnCSwN6+o9b0kP8i107pgERzWYolkp6dWA=","email":"GHm0Re5AMOEXVjmeuscd5JUAswdDQsvqxzzolEXZ75g=","functionCategoryID":"uIPaVTdcTsORfPMM9kjOdoB5Mf5bZShp2eDrt0bhJA8="},{"officeID":"TQ8MQHfCxpu4XMAYJpDcJ9JIGJ\/oZdZTwirC3O9RoRQ=","firstName":"8PIIK6lsX4q9l39oS+ZIlkpKyhnisTVI3d2qa9Rk7IU=","lastName":"8PIIK6lsX4q9l39oS+ZIlkpKyhnisTVI3d2qa9Rk7IU=","userName":"8PIIK6lsX4q9l39oS+ZIlkpKyhnisTVI3d2qa9Rk7IU=","birthdate":"CgQqdhV3+ZnCSwN6+o9b0kP8i107pgERzWYolkp6dWA=","email":"5EID57UhzVapKSu0hPdlU8++ScgjslS5qiqkNGk5Urk=","functionCategoryID":"uIPaVTdcTsORfPMM9kjOdoB5Mf5bZShp2eDrt0bhJA8="},{"officeID":"87Qn9VDRcho3E9SpkkmN3Voow4xbVRrP6Eg1e9q+LTk=","firstName":"j3PjfbjwOyP\/s2kiXWUrFQT33985hJhymjSgyvVWD88=","lastName":"j3PjfbjwOyP\/s2kiXWUrFQT33985hJhymjSgyvVWD88=","userName":"j3PjfbjwOyP\/s2kiXWUrFQT33985hJhymjSgyvVWD88=","birthdate":"aAYSiKoBVvMZ\/x7zZ3fKW8SLDxSNzSguQ2VtpFqn1\/g=","email":"cnHQfIfyGbaSGW9aVPCPkpZ0fxtN2vH8\/Rmhfa61GpU=","functionCategoryID":"uIPaVTdcTsORfPMM9kjOdoB5Mf5bZShp2eDrt0bhJA8="},{"officeID":"fJrhmHvZkTb909xEuy9GBDFTzwmBqOAzJMSdv\/z2NeY=","firstName":"R6UELs10\/qC+e9Iej1Sfh44H53bC1iez1FX9UoBdmL4=","lastName":"dZh5xGkYre\/Qjv\/d8PnYE+0F+YB\/pACDsOhnbT1vC7I=","userName":"u2Q+5N0qfGXguAAXPrjfg27bKcsfn9kmuFirw3D+ESE=","birthdate":"aAYSiKoBVvMZ\/x7zZ3fKW8SLDxSNzSguQ2VtpFqn1\/g=","email":"acpGLJU7viDD8bvDP6cehUtKu4jsu0S7NocWzWI5HsU=","functionCategoryID":"uIPaVTdcTsORfPMM9kjOdoB5Mf5bZShp2eDrt0bhJA8="},{"officeID":"+F8IDemrdYxhfhZRffkcfpC8XRS13jl1zee8jCYZo+k=","firstName":"R6UELs10\/qC+e9Iej1Sfh44H53bC1iez1FX9UoBdmL4=","lastName":"dZh5xGkYre\/Qjv\/d8PnYE+0F+YB\/pACDsOhnbT1vC7I=","userName":"ZaBSv\/5EzxsxaPLVex1m3s0FZ5AAsPHejn1N7qe5lHo=","birthdate":"aAYSiKoBVvMZ\/x7zZ3fKW8SLDxSNzSguQ2VtpFqn1\/g=","email":"dluwI6UQb8M\/eRyaw0YHfX2+kfK2Q1HebrBoQP9Uths=","functionCategoryID":"LwtYJQvWw97ejLbYWRFJn+S5sVKVXvzDXgYat4Le5zQ="},{"officeID":"7jqdChVFIQt5cdXznM5Qmv1EOqgfpi580OHek1L2FVA=","firstName":"R6UELs10\/qC+e9Iej1Sfh44H53bC1iez1FX9UoBdmL4=","lastName":"dZh5xGkYre\/Qjv\/d8PnYE+0F+YB\/pACDsOhnbT1vC7I=","userName":"iShpHaczQ4RtkHVvXmv3nRv8m59qppApLQ99Civ1QlU=","birthdate":"aAYSiKoBVvMZ\/x7zZ3fKW8SLDxSNzSguQ2VtpFqn1\/g=","email":"pq9yUcG+VK5xlHpemKm9B7sE7PxlCdCkFpzhIy\/8k8g=","functionCategoryID":"LwtYJQvWw97ejLbYWRFJn+S5sVKVXvzDXgYat4Le5zQ="},{"officeID":"NkMDOXBeKbSt2jbZNeVaAJaj2V6LUyN9iHVpq4z9YRc=","firstName":"R6UELs10\/qC+e9Iej1Sfh44H53bC1iez1FX9UoBdmL4=","lastName":"dZh5xGkYre\/Qjv\/d8PnYE+0F+YB\/pACDsOhnbT1vC7I=","userName":"GWl7tJfGtL0VXgL2Jn93KO2j4lTHl7vuEpjS5dvrn0E=","birthdate":"aAYSiKoBVvMZ\/x7zZ3fKW8SLDxSNzSguQ2VtpFqn1\/g=","email":"ZLGkTKft82pwTnRJKFWPkE3BFT4WVPt2Qd1P9Og387A=","functionCategoryID":"b3Wl2KsdFOPDVfsrwg2Y347qGc8PM5Yd8UPS+hY7xSk="}],"IsError":"false","ResponsData":"Success"}

My C Sharp

public class Datum
{
public string OfficeID { get; set; }
public string firstName { get; set; }
public string lastName { get; set; }
public string userName { get; set; }
public string birthdate { get; set; }
public string emailEmployee { get; set; }
public string functionCategory { get; set; }
}

public class RootObject
{
public List<Datum> data { get; set; }
public string IsError { get; set; }
public string ErrorMessage { get; set; }
public string ResponseData { get; set; }
}

private async void fillDataGridViewAsync()
{
// Check cache voor session management
checkCache.sessionManagement(cacheSettings.getItem("firstName"));

// Get form data
string searchBox = txtBxSearch.Text.Trim();

// Set encrypted data for transport
string emailSender = CipherForSending.EncryptRJ256(key, iv, email);
string pwdSender = CipherForSending.EncryptRJ256(key, iv, pwd);
string search = CipherForSending.EncryptRJ256(key, iv, searchBox);

// Get connected - Barchart Overview: Visitors
try
{
// request params
var apiUrl1 = "http://www.test.net/plugin/HumanRelations/getData.php";

using (var client1 = new HttpClient())
{
var values1 = new Dictionary<string, string>
{
{ "emailSender", emailSender },
{ "pwdSender", pwdSender },
{ "search", search }
};

var content1 = new FormUrlEncodedContent(values1);

var response1 = await client1.PostAsync(apiUrl1, content1);

var responseString1 = await response1.Content.ReadAsStringAsync();

//Respons r1 = JsonConvert.DeserializeObject<Respons>(responseString1);
RootObject r2 = JsonConvert.DeserializeObject<RootObject>(responseString1);// check response
if (r2.ResponseData == "Success")
{
dgvEmployees.DataSource = r2.data;Cockpit parent = (Cockpit)this.MdiParent;
parent.toolStripLabel2.Text = "Loaded succesfully";
Notifier.setNotifyMessage(parent.notifyIcon1, "You succesfully loaded your columns!!", "Staff Management Message");

}
else
{
ErrorForm ef = new ErrorForm("Error Message", r2.ErrorMessage);
//ef.MdiParent = this;
ef.Show();

Cockpit parent = (Cockpit)this.MdiParent;
parent.toolStripLabel2.Text = "Error";
Notifier.setNotifyMessage(parent.notifyIcon1, "Oops, something went wrong!!", "Error Message");
}
}
}

И мой php:

<?php

include( "library.php" );

try {
if ( $_SERVER[ "REQUEST_METHOD" ] == "POST" ) {
// Post Request
//$Email = strip_tags(isset($_POST['Email']) ? $_POST['Email'] : '');
//$Pwd = strip_tags(isset($_POST['Pwd']) ? $_POST['Pwd'] : '');
$emailSender = strip_tags( isset( $_POST[ 'emailSender' ] ) ? $_POST[ 'emailSender' ] : '' );
$pwdSender = strip_tags( isset( $_POST[ 'pwdSender' ] ) ? $_POST[ 'pwdSender' ] : '' );
$search = strip_tags( isset( $_POST[ 'search' ] ) ? $_POST[ 'search' ] : '' );

$emailSender2 = CipherData::decryptRJ256( $emailSender );
$pwdSender2 = CipherData::decryptRJ256( $pwdSender );
$search2 = CipherData::decryptRJ256( $search );

// Validate Request
if ( empty( $pwdSender2 ) || empty( $emailSender2 ) ) {
throw new Exception( 'Error: Invalid request... Please try again!!' );
}

if ( !empty( $pwdSender2 ) && !empty( $emailSender2 ) ) {

// Set connection
$conn = Connection::Conn_2();

// Sanitize data for query
$emailSender3 = mysqli_real_escape_string( $conn, $emailSender2 );

// Set Password Hash
$hash = new VanillaSpecial;
$hash->Cool_Bananas();
$hash->Salted_Caramel();
$pwd3 = $hash->Hash( $pwdSender2 ); // Hashed Password

//Insert Query of SQL
$result = mysqli_query( $conn, $sql = "SELECT * FROM `Backoffice-employees` WHERE email='$emailSender3' AND password = '$pwd3'" )
or die( json_encode( array(
'IsError' => 'true',
'ErrorMessage' => 'Invalid Request!! Oops, something went wrong. Please try again!!'
) ) );

if ( mysqli_num_rows( $result ) == 1 ) {

// Set connection
$con1 = Connection::Conn_2();

// Sanitize data for query
$search3 = mysqli_real_escape_string( $con1, $search2 );

//Select Query of SQL
$result1 = mysqli_query( $con1, $sql1 = "SELECT * FROM `Backoffice-employees` WHERE userName LIKE '$search3%'" )
or die( json_encode( array(
'IsError' => 'true',
'ErrorMessage' => 'Invalid Request!! Oops, something went wrong. Please try again!!'
) ) );

}

if ( mysqli_num_rows( $result1 ) > 0 ) {

//$respons = array();
//$respons['IsError'] = 'false';
//$respons['ResponseData'] = 'Success';
$row_array = array();
$return_arr = array();
$return_arr['data'] = array();
$return_arr['IsError'] = 'false';
$return_arr['ResponseData'] = 'Success';
$counter = 0;

//array_push($return_arr, $respons);
$return_arr['respons'] = $respons;

// output data of each row
while ( $row1 = mysqli_fetch_assoc( $result1 ) ) {

$row_array['OfficeID'] = encrypt( $row1[ officeID ] );
$row_array['firstName'] = encrypt( $row1[ firstName ] );
$row_array['lastName'] = encrypt( $row1[ lastName ] );
$row_array['userName'] = encrypt( $row1[ userName ] );
$row_array['birthdate'] = encrypt( $row1[ birthdate ] );
$row_array['emailEmployee'] = encrypt( $row1[ email ] );
$row_array['functionCategory'] = encrypt( $row1[ functionCategoryID ] );

//array_push($return_arr, $row_array);
$return_arr['data'][$counter] = $row_array;

$counter++;

}
}

exit( json_encode( $return_arr ) );

}

} else {
throw new Exception( 'Error: Invalid access method!!' );
}

} catch ( Exception $e ) {
exit( json_encode( array(
'IsError' => 'true',
'ErrorMessage' => $e->getMessage()
) ) );
}
?>

Это ошибка, которую я получаю:
System.NullReferenceException: De objectverwijzing является хорошим примером того, как этот объект принимается.
bij HBI_Workflow_Management.Items.StaffManagement.d__14.MoveNext () в C: \ Users \ Jasper \ Documents \ visual studio 2017 \ Проекты \ Пользовательский интерфейс управления рабочим процессом HBI \ Управление рабочим процессом HBI \ Items \ StaffManagement.cs: regel 311

0

Решение

Я попробовал вашу строку JSON, написав этот код, и это прекрасно работает:

namespace testjson
{
public class Datum
{
public string OfficeID { get; set; }
public string firstName { get; set; }
public string lastName { get; set; }
public string userName { get; set; }
public string birthdate { get; set; }
public string emailEmployee { get; set; }
public string functionCategory { get; set; }
}

public class RootObject
{
public List<Datum> data { get; set; }
public string IsError { get; set; }
public string ErrorMessage { get; set; }
public string ResponseData { get; set; }
}
class Program
{
static void Main(string[] args)
{
string jString= @"{ 'data':[{'officeID':'L4UFJw8GpQPg8iryJlHgeQ8L9wvGaGMozF33HxYrouY=','firstName':'R6UELs10\/qC+e9Iej1Sfh44H53bC1iez1FX9UoBdmL4=','lastName':'dZh5xGkYre\/Qjv\/d8PnYE+0F+YB\/pACDsOhnbT1vC7I=','userName':'oJ9SUemStHW6XGJrRSgQJxBUxHIWKejj3yVjbxiNHH8=','birthdate':'386TvajxJiPRXU4UT5OIqH3jmgSqqmv+n09tqxR9458=','email':'1kuUiACYGwkHseT32NfCbb6QH68Mq09ur5LdBo2SzUhdD6mWQjN9leekZrcZVmzcVCfSA4iEgTIspS3j8naYjg==','functionCategoryID':'79kSmrt7HmEYhqBd+NGd8la3NRVkSaeU+9rx7ri\/jG0='},{'officeID':'Ue86sZNLpM0dZXDBbAw4bgpg36te\/Uym3j\/7c\/RK6So=','firstName':'OK6EiNwnB7Ixb25ua62Us1sCMQ3VlGrjAawtU5pamFk=','lastName':'OK6EiNwnB7Ixb25ua62Us1sCMQ3VlGrjAawtU5pamFk=','userName':'OK6EiNwnB7Ixb25ua62Us1sCMQ3VlGrjAawtU5pamFk=','birthdate':'CgQqdhV3+ZnCSwN6+o9b0kP8i107pgERzWYolkp6dWA=','email':'GHm0Re5AMOEXVjmeuscd5JUAswdDQsvqxzzolEXZ75g=','functionCategoryID':'uIPaVTdcTsORfPMM9kjOdoB5Mf5bZShp2eDrt0bhJA8='},{'officeID':'TQ8MQHfCxpu4XMAYJpDcJ9JIGJ\/oZdZTwirC3O9RoRQ=','firstName':'8PIIK6lsX4q9l39oS+ZIlkpKyhnisTVI3d2qa9Rk7IU=','lastName':'8PIIK6lsX4q9l39oS+ZIlkpKyhnisTVI3d2qa9Rk7IU=','userName':'8PIIK6lsX4q9l39oS+ZIlkpKyhnisTVI3d2qa9Rk7IU=','birthdate':'CgQqdhV3+ZnCSwN6+o9b0kP8i107pgERzWYolkp6dWA=','email':'5EID57UhzVapKSu0hPdlU8++ScgjslS5qiqkNGk5Urk=','functionCategoryID':'uIPaVTdcTsORfPMM9kjOdoB5Mf5bZShp2eDrt0bhJA8='},{'officeID':'87Qn9VDRcho3E9SpkkmN3Voow4xbVRrP6Eg1e9q+LTk=','firstName':'j3PjfbjwOyP\/s2kiXWUrFQT33985hJhymjSgyvVWD88=','lastName':'j3PjfbjwOyP\/s2kiXWUrFQT33985hJhymjSgyvVWD88=','userName':'j3PjfbjwOyP\/s2kiXWUrFQT33985hJhymjSgyvVWD88=','birthdate':'aAYSiKoBVvMZ\/x7zZ3fKW8SLDxSNzSguQ2VtpFqn1\/g=','email':'cnHQfIfyGbaSGW9aVPCPkpZ0fxtN2vH8\/Rmhfa61GpU=','functionCategoryID':'uIPaVTdcTsORfPMM9kjOdoB5Mf5bZShp2eDrt0bhJA8='},{'officeID':'fJrhmHvZkTb909xEuy9GBDFTzwmBqOAzJMSdv\/z2NeY=','firstName':'R6UELs10\/qC+e9Iej1Sfh44H53bC1iez1FX9UoBdmL4=','lastName':'dZh5xGkYre\/Qjv\/d8PnYE+0F+YB\/pACDsOhnbT1vC7I=','userName':'u2Q+5N0qfGXguAAXPrjfg27bKcsfn9kmuFirw3D+ESE=','birthdate':'aAYSiKoBVvMZ\/x7zZ3fKW8SLDxSNzSguQ2VtpFqn1\/g=','email':'acpGLJU7viDD8bvDP6cehUtKu4jsu0S7NocWzWI5HsU=','functionCategoryID':'uIPaVTdcTsORfPMM9kjOdoB5Mf5bZShp2eDrt0bhJA8='},{'officeID':'+F8IDemrdYxhfhZRffkcfpC8XRS13jl1zee8jCYZo+k=','firstName':'R6UELs10\/qC+e9Iej1Sfh44H53bC1iez1FX9UoBdmL4=','lastName':'dZh5xGkYre\/Qjv\/d8PnYE+0F+YB\/pACDsOhnbT1vC7I=','userName':'ZaBSv\/5EzxsxaPLVex1m3s0FZ5AAsPHejn1N7qe5lHo=','birthdate':'aAYSiKoBVvMZ\/x7zZ3fKW8SLDxSNzSguQ2VtpFqn1\/g=','email':'dluwI6UQb8M\/eRyaw0YHfX2+kfK2Q1HebrBoQP9Uths=','functionCategoryID':'LwtYJQvWw97ejLbYWRFJn+S5sVKVXvzDXgYat4Le5zQ='},{'officeID':'7jqdChVFIQt5cdXznM5Qmv1EOqgfpi580OHek1L2FVA=','firstName':'R6UELs10\/qC+e9Iej1Sfh44H53bC1iez1FX9UoBdmL4=','lastName':'dZh5xGkYre\/Qjv\/d8PnYE+0F+YB\/pACDsOhnbT1vC7I=','userName':'iShpHaczQ4RtkHVvXmv3nRv8m59qppApLQ99Civ1QlU=','birthdate':'aAYSiKoBVvMZ\/x7zZ3fKW8SLDxSNzSguQ2VtpFqn1\/g=','email':'pq9yUcG+VK5xlHpemKm9B7sE7PxlCdCkFpzhIy\/8k8g=','functionCategoryID':'LwtYJQvWw97ejLbYWRFJn+S5sVKVXvzDXgYat4Le5zQ='},{'officeID':'NkMDOXBeKbSt2jbZNeVaAJaj2V6LUyN9iHVpq4z9YRc=','firstName':'R6UELs10\/qC+e9Iej1Sfh44H53bC1iez1FX9UoBdmL4=','lastName':'dZh5xGkYre\/Qjv\/d8PnYE+0F+YB\/pACDsOhnbT1vC7I=','userName':'GWl7tJfGtL0VXgL2Jn93KO2j4lTHl7vuEpjS5dvrn0E=','birthdate':'aAYSiKoBVvMZ\/x7zZ3fKW8SLDxSNzSguQ2VtpFqn1\/g=','email':'ZLGkTKft82pwTnRJKFWPkE3BFT4WVPt2Qd1P9Og387A=','functionCategoryID':'b3Wl2KsdFOPDVfsrwg2Y347qGc8PM5Yd8UPS+hY7xSk='}],'IsError':'false','ResponsData':'Success'}";
var yourObject =  JsonConvert.DeserializeObject<RootObject>(jString);
}

}
Я использовал библиотеку Newtonsoft, как это предлагает Microsoft, я понятия не имею о библиотеке, которую вы использовали.
Еще одна вещь, которая может вызвать проблему, это двойные кавычки, которые вы использовали для своего json. Если я хочу сохранить их, я должен добавить обратную косую черту перед ними, что вызвало еще одну проблему с косой чертой в коде, поэтому я просто изменил их на одинарные кавычки, а затем Ваша строка JSON действительна и работает нормально.

0

Другие решения

Других решений пока нет …

По вопросам рекламы [email protected]