質問

I made a JSONObject in java and are trying to use the pretty print function from gson to made the object more readable on the website, but it keeps showing as;

{"Back Door":"Unlocked","Window 2":"Unlocked","Window 3":"Unlocked","Window 1":"Unlocked","Front Door":"Unlocked","System":"Disarmed","Lights":"On"}

This is the code I've got so far using gson-2.2.4-javadoc.jar, gson.2.2.4-sources.jar and gson.2.2.4 jar files;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

@Get("json")
public String handleGet() {
    try {
        JSONObject system = new JSONObject();

        system.put("System", "Disarmed");
        system.put("Front Door", "Unlocked");
        system.put("Back Door", "Unlocked");
        system.put("Window 1", "Unlocked");
        system.put("Window 2", "Unlocked");
        system.put("Window 3", "Unlocked");
        system.put("Lights", "On");

        Gson gson = new GsonBuilder().setPrettyPrinting().create();
        System.out.println( gson.toJson(system) );

        JsonRepresentation jsonRep = new JsonRepresentation(system);

        return jsonRep.getText();
    } catch (JSONException e) {
        e.printStackTrace();
    } catch (IOException e)
    {
        e.printStackTrace();
    }
    return null;
}

EDIT

after editing the code like this;

Gson gson = new GsonBuilder().setPrettyPrinting().create();
System.out.println( gson.toJson(system) );

//JsonRepresentation jsonRep = new JsonRepresentation(system);

String pretty = gson.toJson(system);
return pretty;

//return jsonRep.getText();

} catch (JSONException e) {
e.printStackTrace();
//} catch (IOException e)
{
e.printStackTrace();
}
return null;
}
}

and now it shows as;

{
  "map": {
    "Back Door": "Unlocked",
    "Window 2": "Unlocked",
    "Window 3": "Unlocked",
    "Window 1": "Unlocked",
    "Front Door": "Unlocked",
    "System": "Disarmed",
    "Lights": "On"
  }
}

Is there any way to change 'map' to 'system'?

役に立ちましたか?

解決

Just return the pretty printed Gson output

String pretty = gson.toJson(system);
return pretty;

which has the value

{
  "Lights": "On",
  "Front Door": "Unlocked",
  "Window 3": "Unlocked",
  "Window 2": "Unlocked",
  "System": "Disarmed",
  "Back Door": "Unlocked",
  "Window 1": "Unlocked"
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top