Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
96 views
in Technique[技术] by (71.8m points)

c# - JSON data not always called and wrong info in listbox

The listbox is displaying nothing from the JSON data and sometimes will. What is being displayed in the listbox is "OK - System.Collections.Generic.List1[System.String] - System.Collections.Generic.List1[ClassLibraryApi.Report]" and when not throws this exception "System.NullReferenceException: 'Object reference not set to an instance of an object.'" So what did I do wrong?

       {
            ReportViewlistbox.Items.Clear();
            GetReport p = new GetReport();
            var client = new RestClient(p.WebGetReport);
            client.Timeout = -1;
            var request = new RestRequest(Method.POST);
            request.AddHeader("Content-Type", "Value");
            request.AddHeader("Content-Type", "Value");
            var thisJsonStr = "{"Credentials":{"ApiKey":"string (CompactGUID)","MerchantID":"string","StoreID":"string","Username":"string","Password":"string"}}", ParameterType.RequestBody);
            request.OnBeforeDeserialization = resp => { resp.ContentType = "application/json"; };
            request.AddParameter("application/json", thisJsonStr, ParameterType.RequestBody);
            IRestResponse response = client.Execute(request);
            var viewreport = Viewreport.FromJson(response.Content);
            ReportViewlistbox.Items.Add($"{viewreport.Result} - {viewreport.ReportHeader} - {viewreport.Reports}");

        }

and my class is

 public partial class Viewreport
{
    [JsonProperty("Result")]
    public string Result { get; set; }

    [JsonProperty("ReportHeader")]
    public List<string> ReportHeader { get; set; }

    [JsonProperty("Reports")]
    public List<Report> Reports { get; set; }
}

public partial class Report
{
    [JsonProperty("ReportID")]
    [JsonConverter(typeof(ParseStringConverter))]
    public long ReportId { get; set; }

    [JsonProperty("ReportTxt")]
    public List<string> ReportTxt { get; set; }
}

public partial class Viewreport
{
    public static Viewreport FromJson(string json) => JsonConvert.DeserializeObject<Viewreport>(json, ClassLibraryApi.Converter.Settings);
}

public static class Serialize
{
    public static string ToJson(this Viewreport self) => JsonConvert.SerializeObject(self, ClassLibraryApi.Converter.Settings);
}

internal static class Converter
{
    public static readonly JsonSerializerSettings Settings = new JsonSerializerSettings
    {
        MetadataPropertyHandling = MetadataPropertyHandling.Ignore,
        DateParseHandling = DateParseHandling.None,
        Converters =
        {
            new IsoDateTimeConverter { DateTimeStyles = DateTimeStyles.AssumeUniversal }
        },
    };
}

internal class ParseStringConverter : JsonConverter
{
    public override bool CanConvert(Type t) => t == typeof(long) || t == typeof(long?);

    public override object ReadJson(JsonReader reader, Type t, object existingValue, JsonSerializer serializer)
    {
        if (reader.TokenType == JsonToken.Null) return null;
        var value = serializer.Deserialize<string>(reader);
        long l;
        if (Int64.TryParse(value, out l))
        {
            return l;
        }
        throw new Exception("Cannot unmarshal type long");
    }

    public override void WriteJson(JsonWriter writer, object untypedValue, JsonSerializer serializer)
    {
        if (untypedValue == null)
        {
            serializer.Serialize(writer, null);
            return;
        }
        var value = (long)untypedValue;
        serializer.Serialize(writer, value.ToString());
        return;
    }

    public static readonly ParseStringConverter Singleton = new ParseStringConverter();
}

}

This what I see in postman

{
"Result": "OK",
"ReportHeader": [
    "     Company: Pizza  - Pearl",
    "    Run Time: 02/05/21 09:27AM",
    "Reporting On: Current #1"
],
"Reports": [
    {
        "ReportID": "34",
        "ReportTxt": [
            " ",
            "REPORT GROUP: MANDY REPORT",
            "--------------------------------",
            " ",
            "REPORT PRESET: Employee Hours",
            " ",
            " ",
            "EMPLOYEE SHIFTS:",
            " ",
            "    Employee           Job          Time In        Time Out       Reg     OT     Hours     Pay   ",
            "----------------|--------------|---------------|---------------|-------|-------|-------|---------",
            "F, Tanner       |MANAGER       |02/05/21 08:32A|02/05/21 09:27A|   0.93|   0.00|   0.93|    15.14",
            "----------------|--------------|---------------|---------------|-------|-------|-------|---------",
            "                |              |               |               |   0.93|   0.00|   0.93|    15.14"
        ]
    }
]

}

question from:https://stackoverflow.com/questions/66066254/json-data-not-always-called-and-wrong-info-in-listbox

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...