safa
safa

Reputation: 17

JSON error message

i wrote this JSON code

public class TestClass {

    public static void main(String[] args) {
        String inputJson= "{" +"\"contexts\" : {  "+ "{ " + "\"times\" : { " + "{  " + "\"end\":17, " + "\"begin\" : 9 " +  "}" + "}," +    "\"contextname\":\"OFFICE_HOURS\" " +   "}," + "{ " + "\"days\": { " + "\"MON\", " +    "\"TUE\", " + "\"WED\" , " + "\"THU\", " +  "\"FRI\" " +    "} , " + "\"contextname\" : \"WORKDAYS\" " +    "}";
        ObjectMapper mapper= new ObjectMapper();
        mapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);

        try {

            MainParser mp= mapper.readValue(inputJson, MainParser.class);

            System.out.println(mp.getContextname());
        }

but i found this error in the console box

org.codehaus.jackson.JsonParseException: Unexpected character ('{' (code 123)): was expecting double-quote to start field name
 at [Source: java.io.StringReader@7cf10a6f; line: 1, column: 19]

i need help please

Upvotes: 0

Views: 166

Answers (2)

Dharmendra Rathor
Dharmendra Rathor

Reputation: 77

Following is Json string as per code. It is not in correct json format.

{"contexts" : { { "times" : { { "end":17, "begin" : 9 }},"contextname":"OFFICE_HOURS" },{ "days": { "MON", "TUE", "WED" , "THU", "FRI" } , "contextname" : "WORKDAYS" }

Try to fix json string format and run the code again.

Upvotes: 0

antasp
antasp

Reputation: 304

When formatted your JSON looks like this:

{
  "contexts": {
    {
      "times": {
        {
          "end": 17,
          "begin": 9
        }
      },
      "contextname": "OFFICE_HOURS"
    },
    {
      "days": {
        "MON",
        "TUE",
        "WED",
        "THU",
        "FRI"
      },
      "contextname": "WORKDAYS"
    }

This is not valid, for multiple reasons.

You could make it valid by replacing the content of "contexts" with an array and wrapping the days in an array, and removing some extra curly brackets.

{
  "contexts": [
    {
      "times": {
        "end": 17,
        "begin": 9
      },
      "contextname": "OFFICE_HOURS"
    },
    {
      "days": [
        "MON",
        "TUE",
        "WED",
        "THU",
        "FRI"
      ],
      "contextname": "WORKDAYS"
    }
  ]
}

A better way may be to use the "contextname" values as keys and simplifying the whole JSON.

{
  "OFFICE_HOURS": {
    "end": 17,
    "begin": 9
  },
  "WORKDAYS": [
    "MON",
    "TUE",
    "WED",
    "THU",
    "FRI"
  ]
}

Upvotes: 2

Related Questions