How can I parse json using Java (android) [duplicate] - java

This question already has answers here:
How do I parse JSON in Android? [duplicate]
(3 answers)
Closed 6 years ago.
I have a JSON string and I need to extract a string from it using Java (android)
The JSON string look like that :
{
"Header": {
"context": {
"change": {
"token": 3191
},
"_jsns": "urn:zimbra"
}
},
"Body": {
"AuthResponse": {
"authToken": [
{
"_content": "token"
}
],
"lifetime": 43199998,
"_jsns": "urn:zimbraAdmin"
}
},
"_jsns": "urn:zimbraSoap"
}
I want to get the value of _content, which is "token" is this case.
What i tried:
NB: result contains the json string
//result contains the json string
JSONObject jObject = new JSONObject(result);
String aJsonString = jObject.getString("Body");
JSONObject jResult = new JSONObject(aJsonString);
String aaa = jResult.getString("authToken");
At this point I get the following error :
W/System.err: org.json.JSONException: No value for authToken
Any help will be appreciated
EDIT : Java code updated

You need to traverse the JSON tree step by step
JSONObject jObject = new JSONObject(result);
JSONObject jBody = jObject.getJSONObject("Body");
JSONObject jAuthResponse = jBody.getJSONObject("AuthResponse");
JSONArray jauthToken = jAuthResponse.getJSONArray("authToken");
JSONObject jFirst = jauthToken.getJSONObject(0);
String aJsonString = jObject.getString("_content");

Related

Parsing JSON to Java Entity [duplicate]

This question already has answers here:
How to parse JSON in Java
(36 answers)
Closed 2 years ago.
Any idea how I can parse a Json like this into a java entity?
{
"-MR0myiEK5jDOdthWeMT": {
"birthday": "Date5",
"name": "Check 1"
},
"-MR0n-86JCqxuO7C2HfZ": {
"birthday": "Date3",
"name": "Check 2"
},
"-MR0n0VCXBw-32tfq738": {
"birthday": "Date1",
"name": "Check 4"
}
}
I am using spring and wanted to parse it into a java class like this:
class Person{
String name;
String birthday;
}
The org.json library is easy to use.
Just remember (while casting or using methods like getJSONObject and getJSONArray) that in JSON notation
[ … ] represents an array, so library will parse it to JSONArray
{ … } represents an object, so library will parse it to JSONObject
Example code below:
import org.json.*;
String jsonString = ... ; //assign your JSON String here
JSONObject obj = new JSONObject(jsonString);
String pageName = obj.getJSONObject("pageInfo").getString("pageName");
JSONArray arr = obj.getJSONArray("posts"); // notice that `"posts": [...]`
for (int i = 0; i < arr.length(); i++)
{
String post_id = arr.getJSONObject(i).getString("birthday");
......
}
I would use the
jackson
library that is already included in the spring boot dependencies.

Java json exception [duplicate]

This question already has an answer here:
org.json.JSONException: JSONObject["address"] is not a JSONArray
(1 answer)
Closed 5 years ago.
Using this code to call steam api. Parsing json gives me some problems. I manage to print the json in the console, accessing furhter data fails. Here is my code:
JSONObject json = new JSONObject(IOUtils.toString(new URL("http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key=XXXXXXX&steamids=XXXXXXX"), Charset.forName("UTF-8")));
System.out.println(json.get("response")); >>> (1)
int out = json.getJSONObject("players").getInt("steamid");
System.out.println(out);
Exception in thread "main" org.json.JSONException: JSONObject["players"] not found.
{
"response": {
"players": [
{
"steamid": "XXXXX",
"communityvisibilitystate": 3,
"profilestate": 1,
"personaname": "XXXXX",
"lastlogoff": 123123,
"profileurl": "http://steamcommunity.com/id/XXX/",
"avatar": "XXXXX",
"avatarmedium": "XXXX",
"avatarfull": "XXXXX",
"personastate": 1,
"primaryclanid": "XXX",
"timecreated": XXX,
"personastateflags": 0,
"gameextrainfo": "Tom Clancy's Rainbow Six Siege",
"gameid": "359550"
}
]
}
}
You just need to understand the difference between JSONObject structure and JSONArray structure
The JSONObject will starts with "{", and JSONArray starts with "[".
I just noticed your mistake, you didnt assign json.get("response") to any variable.
JSONObject json = new JSONObject(IOUtils.toString(new URL("http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key=XXXXXXX&steamids=XXXXXXX"), Charset.forName("UTF-8")));
System.out.println(json.get("response"));
JSONObject playersJson=json.get("response");
int out = playersJson.getJSONArray("players").getJSONObject(0).getInt("steamid");
So try changing your code as above.
Your problem is that players is not a JSONObject, it's a JSONArray which contains JSONObjects. In this case, players contains one JSONObject, so you need to access that object first using players[0]:
int out = json.getJSONArray("players")[0].getInt("steamid");

How do I extract the specific date out in Java? [duplicate]

This question already has answers here:
How to parse JSON in Java
(36 answers)
Closed 6 years ago.
I am currently using bufferreader to read an API documentation. Below is part of the output:
"number": 88,
"results": [
{
"time": "2013-04-15T18:05:02",
"name": "..."
},
{
"time": "2013-05-01T18:05:00",
"name": "..."
},
...
]
If I want to extract only "2013-04-15T18:05:02", which is the date. How can I do that?
You can use minimal json.
The following snippet extracts the dates and id's of all items:
JsonObject object = Json.parse(output).asObject();
JsonArray results = object.get("results").asArray();
for (JsonValue item : results) {
String date = item.asObject().getString("date", "");
String id = item.asObject().getString("id", "");
...
}
The format of your string seems to be JSON. You can use Jackson API to parse the JSON string into an array. If you don't want to use Jackson or other JSON API, you can still do it using some of the java.util.String class methods. Checkout the following sample:
List<String> dates = new ArrayList<String>();
String results = jsonString.substring(jsonString.indexOf("results"));
while((int index = results.indexOf("\\"date\\"")) != -1) {
String date = results.substring(results.indexOf(':', index), results.indexOf(',', index)).replaceAll(" ", "").replaceAll("\\"", "");
dates.add(date);
results = results.substring(results.indexOf(',', index));
}

Parsing JSON in Java when two fields are the same? [duplicate]

This question already has answers here:
Parsing JSON Array within JSON Object
(5 answers)
Closed 6 years ago.
Apologies, I have tried multiple things here and seem to run into some issues. This should be simple.
JSON file :
{
"content": [
{
"media_type": "text/html",
"text": "<p>Hello world</p>"
},
{
"media_type": "text/plain",
"text": "Hello world"
}
],
"id": "123",
"title": "no-title"
}
I have a JSONObject created from this string.
I have tried -
String txtFromJSON = json.getJSONObject("content").getJSONObject("text").toString();
String txtFromJSON = json.getString("content.text");
String txtFromJSON = json.getString("content");
All of these fail.
The output I would like is simply the
<p>Hello world<p>
from the first text field.
Is there any simple way for me to get this data stored in a variable?
Thanks.
try this:
final JSONObject obj = new JSONObject(youJsonString);
final JSONObject content = obj.getJSONArray("content");
final int n = content.length();
if(n ==1 ){
String txtFromJSON = json.getString("text");
}

How to fetch the JSON data in java [duplicate]

This question already has answers here:
How to parse JSON in Java
(36 answers)
Closed 8 years ago.
I have a JSON string:
[
{
"customer": {
"created_at": "2014-05-22T18:24:55+05:30",
"cust_identifier": null,
"description": null,
"domains": null,
"id": 1000170724,
"name": "freshdesk",
"note": null,
"sla_policy_id": 1000042749,
"updated_at": "2014-05-22T18:24:55+05:30"
}
}
]
How to get the value of id using java?
Use JSONObject and JSONArray
int id = new JSONArray(my_json_string).getJSONObject(0).getJSONObject("customer").getInteger("id");
More informations on JSON in java here : http://www.json.org/java/
You can use Googles Gson.
Here is a little example:
Gson gson = new Gson();
int id;
try {
// read file
FileInputStream input = new FileInputStream("cutomer.json");
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
// read file as JSON Object
JsonObject json = gson.fromJson(reader, JsonObject.class);
// read attribut "customer" as array
JsonArray customers = json.getAsJsonArray("customer");
JsonObject cutomer= customers.get(0).getAsJsonObject();
// Attribute ausgeben z.B.: name, alter und hobbies
id = customer.get("is").getAsInt());
} catch (FileNotFoundException e) {
e.printStackTrace();
}

Categories