Escaping slash and other characters when using JsonObject? - java

I did search on the internet but couldn't find a solution for me, this is the resulting JsonString when using Gson to convert my Object:
JSONObject obj = new JSONObject();
String tmp;
tmp = gson.toJson(request);
{"_Json":"{LastName=ho, BirthDate=2017/10/06 08:47:29, FirstName=hey, Password=1, Email=letsgo}","_Token":"","_UserID":0}
Thats the actual Value I want to have in my JsonObject too but when I put this JsonString in my JsonObject the simple / are now / and I have no clue how I can get rid of this because I want to send this JsonObject via Post to create a user:
obj = new JSONObject(tmp);
{"_Json":"{LastName=ho, BirthDate=2017\/10\/06 08:47:29, FirstName=hey, Password=1, Email=letsgo}","_Token":"","_UserID":0}
I had a similar problem with gson when converting it in a JsonString but this simply solved by using:
Gson gson = new GsonBuilder().disableHtmlEscaping().create();

Related

How to retreive data from Json using java

hi guys i have json response like this
Response response = service.execute(requestSendToNS);
// JSONObject jsonResponse = new JSONObject(response);
//String data = jsonResponse.getString("id");
System.out.println("Response Body : " + response.getBody());
and here the result :
Response Body : [{"status":"success","message":"update success","id":"1404","internalid":2604},{"status":"failed","message":"bad location is already used in another location","id":1405}]
my question is how to getting value "id" from my json response ?
i have try use this code :
// JSONObject jsonResponse = new JSONObject(response);
//String data = jsonResponse.getString("id");
i also have use this
List responseObject = objectMapper.readValue(response.getBody(),List);
but i cannot mapping from json Array to object
but i cannot retreive value from id
Your response body is an array.
[{...},{...}]
That's why you can't get id
String data = jsonResponse.getString("id");
Please have a look JsonReader to read json as JsonArray
https://docs.oracle.com/javaee/7/api/javax/json/JsonReader.html#readObject--
JsonReader jsonReader = Json.createReader(new StringReader(response.getBody()));
JsonArray array = jsonReader.readArray();
JsonObject obj = array.getJsonObject(0);
String data = obj.getString("id");
First, you have to create a class that has the exact same structure as the JSON response, and then you can use ObjectMapper from jackson library to write the JSON to class and read the values from it.

Convert a gson.JsonObject to JSONObject

I have a gson.JsonObject object. What is the easiest way to create a org.json.JSONObject object from it?
get JSON string again from JsonObject and parse it in JSONObject
JsonObject gson = new JsonParser().parse("{\"id\":\"value\"}").getAsJsonObject();
JSONObject jo2 = new JSONObject(gson.toString());
new org.json.JSONObject(gson.toJson(gson.JsonObject));

Deciphering JSON from AcousticBrainz

I stumbled upon AcousticBrainz and I am trying to get the data from their database. They give me the API (acousticbrainz.org/api). Unfortunatley I am new to JSON and
I am not exactly sure how to get the info. I am trying to get the info from
http://acousticbrainz.org/8e160042-b451-4f96-b59a-d06831d2ae05/high-level
I know that there are only two JSON Objects. "highlevel" and "metadata"
This is how they present their info
http://acousticbrainz.org/8e160042-b451-4f96-b59a-d06831d2ae05
I am coding in Java and this is what I have
String URL = "http://acousticbrainz.org/8e160042-b451-4f96-b59a-d06831d2ae05/high-level";
String Json = IOUtils.toString(new URL(URL));
JSONObject jo = new JSONObject(Json);
JSONObject jom = new JSONObject(jo.get("metadata"));
System.out.println(jo.names());
System.out.println(jom.names());
System.out.println(jo.get("metadata"));
If you are looking to make API call and get the json data you can use the following code:
URIBuilder builder = new URIBuilder().setScheme("http")
.setHost("acousticbrainz.org")
.setPath("/8e160042-b451-4f96-b59a-d06831d2ae05/high-level");
HttpUriRequest httpUriRequest = new HttpGet(builder.build());
HttpResponse httpResponse = HttpClientBuilder.create().build().execute(httpUriRequest);
String response = EntityUtils.toString(httpResponse.getEntity());
JSONObject jsonObject = new JSONObject(response);
System.out.println(jsonObject.toString());
And if you want to parse the json data and use it you can check the below sample code:
JSONObject metaDataObject = jsonObject.getJSONObject("metadata");
String md5EncodedValue = metaDataObject.getJSONObject("audio_properties")
.getString("md5_encoded");
System.out.println(md5EncodedValue);
if you are using maven then add the following dependency
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20131018</version>
</dependency>
or use this link to download the jar

casting String to JSONObject

I have a json response from server, I get as string, and want to cast to JSONObject (import org.json.JSONObject;)
this is my casting:
JSONObject responseJson = new JSONObject(responseString);
and this is what I get:
responseString = {"code":0,"type":"success","description":null,"data":{"path":"http:........"}}
responseJson = {"class":"class java.lang.StringBuilder"}
does anyone knows why is responseJson not with correct values?
I can do
responseJson.getString("class")
but what I want to do is
responseJson.getString("type")
Try this way with json-simple
String jsonString = "{\"code\":0,\"type\":\"success\",\"description\":null,\"data\":
{\"path\":\"http:........\"}}";
org.json.simple.JSONObject json =(org.json.simple.JSONObject) new JSONParser()
.parse(jsonString);
System.out.println(json.get("data"));

How to put JSON information in an array to use it for displaying in ListView

I have an Activity which has three fragments and I am trying to retrieve a JSON file from my server which I will be updating on a daily basis.
My JSON file is located here: http://pagesbyz.com/test.json
Because there are fragments, I used the following code in my MainActivity class:
DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
HttpPost httppost = new HttpPost("http://pagesbyz.com/test.json");
// Depends on your web service
httppost.setHeader("Content-type", "application/json");
InputStream inputStream = null;
String result = null;
try {
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
inputStream = entity.getContent();
// json is UTF-8 by default
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
result = sb.toString();
Toast.makeText(getApplicationContext(), result, 2000).show();
} catch (Exception e) {
// Oops
}
finally {
try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
}
What I really need to do is retrieve the TYPE field in my JSON file and separate it into three tabs and put it inside a ListView like this:
I would like to know once I have read the JSON file by using the code on top how do I proceed... Thanks for the help :)
Should I query on each fragment and then look for the TYPE field? Would that be easier?
Curious as to why the Toast did not execute... Here is the pastebin for my main activity: http://pastebin.com/gKTCeH79
What you want to do is use Androids JSONObject and JSONArray to access your json data.
For example since your root is a json array you want to instantiate a JSONArray object from your json data you have.
JSONArray jsonArray = new JSONArray(jsonString);
Now from this array you can grab individual JSONObject for each object in your array.
JSONObject objectOne = new JSONObject(0); // Grabs your first item
From the JSONObject you can now access your three values.
String type = objectOne.get("type") // Will give you the value for type
JSONArray: http://developer.android.com/reference/org/json/JSONArray.html
JSONObject: http://developer.android.com/reference/org/json/JSONObject.html
Another way is to use a framework that lets you deserialize json into Java POJO's (Plain Old Java Objects). Gson is the easiest to use.
The basic idea is you make an object that relates directly to your json objects, after you have this you can easily store your data in java objects and use it however you like.
GSON example:
Gson gson = new Gson();
MyCustomClass obj2 = gson.fromJson(json, MyCustomClass.class);
Where MyCustomClass would contain the variables id, type, and data.
GSON reference: https://sites.google.com/site/gson/gson-user-guide
Good Luck!

Categories

Resources