0

Pretty simple thing to do and I can't figure this one out for some reason. I have a mock JSON file that looks like so:

  {
  "AccountId":"XXXXXXXXX",
  "UAN":"PE3458234758345",
  "BillingName":"John Smith",
  "BillingAddress": {
    "Address1":"701 First Ave.",
    "Address2":"test",
    "City":"Philadelphia",
    "State":"PA",
    "Zip:":"19147"
  },
  "ServiceStartDate":"5/1/2012",
  "PromoCode":"0056",
  "PartnerCode":"AAL",
  "MemberNumber":"0000001",
  "Invoices":[
    {
      "Amount":"113.78",
      "Date":"6/1/2012",
      "Usage":"3143"
    },
    {
      "Amount":"123.56",
      "Date":"7/1/2012",
      "Usage":"4561"
    },
    {
      "Amount":"105.23",
      "Date":"8/1/2012",
      "Usage":"5454"
    }
  ],
  "Expected":[
    {
      "AwardCreation":"true",
      "AwardAmount":"500",
      "AwardUnits":"usd",
      "AwardDate":"today()"
    }
  ]
}

And I'm needing to create a dynamic object from this as this can vary each time a test mockup is ran. I've tried the custom deserializer as noted in this solutio as well as the .NET 4.0 System.Web.Helpers and in both cases I end up with:

Invalid JSON primitive: \0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0...

Currently my working test is:

var json = new StringBuilder();

        using (var fs = File.Open(@"c:\users\bryan\Desktop\test2.json", FileMode.Open))
        {
            var byteArray = new byte[1024];
            var tempString = new UTF8Encoding(true);

            while (fs.Read(byteArray, 0, byteArray.Length) > 0)
            {
                json.Append(tempString.GetString(byteArray));
            }
        }

       var dynamicObject = Json.Decode(json.ToString());

       Assert.IsNotNull(dynamicObject);

I have no clue, I guess it's the format? I've stripped everything out of the json file (meaning one giant line) and I get the same thing. Oddly, when I use Newtonsoft.Json I don't get the error, but the dynamic object is just the AccountId string and nothing else.

Community
  • 1
  • 1
bryan
  • 1,031
  • 2
  • 17
  • 36

1 Answers1

2

You code to read UTF-8 file is wrong as it:

  • tries to convert potentially incomplete byte sequences due to cutting of on 1024 bytes boundary
  • appends extra 0 bytes due to ignoring length of the file in last segment.

Consider using StreamReader or some other built in method to read string from file. See How to:Read Text from a File and File.ReadAllText for starting points.

var dynamicObject = Json.Decode(
  File.ReadAllText(@"c:\users\bryan\Desktop\test2.json"));
Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179