0

I have some wpf app where I store data based on user's input in some local json file. roughly it looks something like:

{
  "Database": {
    "instance": "",
    "userName": "",
    "password": "",
  },
       "Website": {
    "ip": "111.111.111.111",
    "port": "8080"
  },
       "User": [],
  "ReportService": {
    "instance": "fff",
    "ip": "111.111.121.212",
    "port": "88"
  }
}

suppose I have an "Import" button witch let the user to import other json file.

My question is how to verfity that the imported json file has same structure as mine?

I mean same objects with the fields like username,password,...

Because I want to validate the imported json to verify that he has the same structure as I expect.

Edit:

My solution for now is try, catch but I'm sure that there is more elegant solution

NineBerry
  • 26,306
  • 3
  • 62
  • 93
Flufy
  • 309
  • 2
  • 15
  • Why not import the user JSON and test the resulting object? – sodawillow May 26 '18 at 09:32
  • possible duplicate: https://stackoverflow.com/questions/19544183/validate-json-against-json-schema-c-sharp – Thomas D. May 26 '18 at 09:33
  • @ThomasD. can't see how it helps. plz post answers – Flufy May 26 '18 at 10:05
  • you want to validate a given json, so you have basically two options: Either you implement a parser/validator yourself (which it looks to me you don't want to - which i totally understand) or you could use some 3rd party stuff for your validation. The link from me shows a take on with JSON schema – Thomas D. May 26 '18 at 11:36

2 Answers2

1

Specifiy object and then serialize and deserialize to it instead of JObject in JSON.net. so if the deserialization won't work you will be sure schema is changed

Mahesh Malpani
  • 1,782
  • 16
  • 27
0

As Thomas pointed out, defining your own JSON schema for your objects is the way to go. Then you can validate the imported files against this schema e.g. using Json.NET as shown here, since this library is usually the go-to choice for working with JSON on .NET

grepfruit
  • 181
  • 9
  • 1
    Just to note, Json.NET Schema may not be free, depending on your use case, as outlined [here](https://www.newtonsoft.com/store/jsonschema). – Callum Watkins May 26 '18 at 19:58