How to convert String in java to Json - java

How can i convert such a string to json in java?
String mycode = "{
"name": "Test",
"Status": {
"code": 200,
"request": "get"
}
}";
thanks

Using org.json library:
JSONObject jsonObj = new JSONObject(mycode);

I find Google gson to be extremely convenient and (that's not so frequent) to be very light and not leaving traces in your code except in the point where you make the json production (if you don't need specific conversions).
http://code.google.com/p/google-gson/

GSON is a good open source library that would fit your use case. here is the link - http://code.google.com/p/google-gson/

Related

Treves the JSON object and manipulate the value in java

What im trying to do is
JSON:
{
aKey:{
aChildKey:""
},
bKey:""
}
expected:
aKey:{
aChildKey:"aKey.aChildKey"
},
bKey:"bKey"
}
Please can some one help me in getting the expected the value
You need to deserialize the JSON into an object, set the values, then serialize it back into JSON. There are a number of libraries you can use for this, like org.json, gson, or Jackson. Those libraries also allow you to modify the value directly. For example, using org.json, you can do something like this:
JSONObject jsonObject = new JSONObject(myJsonString);
jsonObject.getJSONObject("akey").put("aChildKey","aKey.aChildKey");
See How to parse JSON in Java

Is there a better/easier way to update a json file in Java?

Say, I have a json file like below:
[{
"obj1_key1":"aa",
"obj1_array":[{"e1":"11"},{"e2":"22"}]
},
{
"obj2_key1":"cc",
"obj2_key2":"dd"
}]
Now I want update the file into something like below:
[{
"obj1_key1":"aa",
"obj1_array":[{"e1":"11"},{"e2":"22"},{"e3":"333"}]
},
{
"obj2_key1":"cc",
"obj2_key2":"dd"
}]
I tried using ObjectMapper to parse the file like
JsonNode jsonFile = new ObjectMapper().readTree(new File("file.json");
however then I need to find the obj1_array and append a json object, then write the json object back to the file. And I don't think the way I load the json file as a JsonNode is a easy way because I should convert it between Json/JsonArray back and forth. So I'm wondering is there a simpler way to make this work? Really appreciate that.
if it is just a one-off case, you can use your preferred mechanism, but if it is going to used often, I would prefer
Convert the JSON to a POJO ( using some parser eg Jackson )
Update the requisite fields
Return the Json object.

Database JSON array

So I'm currently building a game, and I'm trying to parse this in the game. Now this is how a part of it looks like:
{
"CircuitList": [
{
"name": "GP SILVERSTONE",
"location": "ENGLAND",
"laps": 57,
"Parts":
[
{
"1":{
"type": "straight",
"length": 800
},
"2": {
"type": "sharpturn",
"length": 200
},
Now this is followed by more parts. Right now, I've parsed the json file, and used
JSONArray Silverstoneparts = (JSONArray) jsonObject.get("Parts");
to create a array with all the parts. But I don't know how to read out the types and lengths, so if there is anyone willing to help, like push me gently into the right direction, it would be highly appreciated :)
JSONArray circuitList = (JSONArray) jsonObject.get("CircuitList");
JsonArray parts = circuitList.getJsonObject(0).getJsonArray("parts");
It's recommend to use JsonObject to build json string.
You can try parsing the JSON using gson library. You should define a data struct with nested arrays/properties as per your JSON data and serialise the JSON data to native object.
Native java object will help you read the parsed arrays and other properties in your code rather being relying on keys and running loops within loops to extract the values.

GSON parsing without a lot of classes

I have the following JSON and I'm only interested in getting the elements "status", "lat" and "lng".
Using Gson, is it possible to parse this JSON to get those values without creating the whole classes structure representing the JSON content?
JSON:
{
"result": {
"geometry": {
"location": {
"lat": 45.80355369999999,
"lng": 15.9363229
}
}
},
"status": "OK"
}
You don't need to define any new classes, you can simply use the JSON objects that come with the Gson library. Heres a simple example:
JsonParser parser = new JsonParser();
JsonObject rootObj = parser.parse(json).getAsJsonObject();
JsonObject locObj = rootObj.getAsJsonObject("result")
.getAsJsonObject("geometry").getAsJsonObject("location");
String status = rootObj.get("status").getAsString();
String lat = locObj.get("lat").getAsString();
String lng = locObj.get("lng").getAsString();
System.out.printf("Status: %s, Latitude: %s, Longitude: %s\n", status,
lat, lng);
Plain and simple. If you find yourself repeating the same code over and over, then you can create classes to simplify the mapping and eliminate repetition.
It is indeed possible, but you have to create a custom deserializer. See Gson documentation here and Gson API Javadoc here for further info. And also take a look at other reponses of mine here and here... and if you still have doubts, comment.
That said, in my opinion it is much easier for you to parse it creating the correspondent classes, even more taking into account the simplicity of your JSON response... With the usual approach you only have to write some super-simple classes, however, writing a custom deserializer, although is not that complex, it will take you probably longer, and it will be more difficult to adapt if later on you need some data else of your JSON...
Gson has a way of operating that has been designed for developers to use it, not for trying to find workarounds!
Anyway, why do you not want to use classes? If you don't like to have many classes in your project, you can just use nested classes and your project will look cleaner...

Create JSON object and convert it to String in Java

I need to send a quite long JSON header through an http post. In Python was like this:
self.body_header = {
"client": self.client_name,
"clientRevision": self.client_version,
"uuid": str(uuid.uuid4()),
"session": self.get_sessionid()}
self.body = {
"header": self.body_header,
"country": {"IPR":"1021", "ID":"223", "CC1":"0", "CC2":"0", "CC3":"0", "CC4":"2147483648"},
"privacy": 1}
I need to do something similar in Java, ie, create somehow a JSON struct, convert it to a String and send it via http.
The question is, how can I achieve that easily? Any useful libraries? I know how to send it, but not how to build it and then create a String.
Thank you all.
You can use gson.
You can create a Java Object (POJO) and serialize it as JSON by doing:
Gson gson = new Gson();
String json = gson.toJson(yourObject);
You can then send the string over HTTP.
If you do not want to go the POJO route, you can still create the JSON struct using JsonElement, JsonArray, JsonObject in the Gson API.
I like the original org.json
i think STO had a similar discussion https://stackoverflow.com/questions/338586/a-better-java-json-library

Categories