0

I get an error while parsing a json string into an object. I am using system.json to parse the json string.

The JSON file: (NOTE: I cannot change the structure of this json file because it is generated)

{
    title: "My Title",
    log: "",                    
    nid: "1234",
    type: "software",
    language: "EN",
    created: "1364480345",
    revision_timestamp: "1366803957",
    body: {                 
         und: [
              {
                  value: "abc",
                  summary: "def"
              }
         ]
    }
}

The C# code:

string jsonString = new WebClient().DownloadString(".......MyJson.json");  //For test purpose

var obj = JsonObject.Parse (jsonString);  ///<--- At this line the exception is thrown 

The Exception:

System.ArgumentException has been thrown.
Invalid JSON string literal format. At line 1, column 2

How to solve this?

Thanks in advance!

StackFlower
  • 691
  • 1
  • 13
  • 29
  • 1
    I expect it is complaining because this is not valid JSON. Those object properties must be enclosed in quotes: `title: "My Title"` should be `"title": "My Title"`. If you cannot change the file, I think maybe Newtonsoft's JSON.Net can handle this sort of format, but I'm not sure; I've not actually tried it. – Chris Nielsen May 09 '13 at 18:13
  • @ChrisNielsen I believe json.NET will throw on that too. – evanmcdonnal May 09 '13 at 18:14

2 Answers2

2

You can't. That isn't valid json. Field names must be enclosed in quotes. All json parsing tools will throw when trying to parse that.

You could process it and turn it to valid json before deserializing, but really, you need to correct it API side. No clients will work with that.

evanmcdonnal
  • 46,131
  • 16
  • 104
  • 115
0

How to solve this?

(NOTE: I cannot change the structure of this json file because it is generated)

Easy, use json.Net. it works without any problem with your json

var j = JObject.Parse(jsonString);

You can even use dynamic keyword

dynamic j = JObject.Parse(jsonString);

Console.WriteLine("{0},{1}", j.title, j.body.und[0].value);
Community
  • 1
  • 1
I4V
  • 34,891
  • 6
  • 67
  • 79
  • 1
    This is great when you've got the freedom to add Nuget packages, but I'm looking for a solution that doesn't involve adding dependencies – Alex Kibler Oct 29 '19 at 15:39