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();
}
Related
I am learning to work with json files and I'm using the JSON-java library from https://github.com/stleary/JSON-java
I was able to manipulate data for this json dataset
{
"timezone": "UTC",
"serverTime": 1602321831628,
"rateLimits": [
{
"rateLimitType": "REQUEST_WEIGHT",
"interval": "MINUTE",
"intervalNum": 1,
"limit": 1200
}
],
"symbols": [
{
"symbol": "ETHBTC",
"status": "TRADING"
}
]
}
Using this code
JSONTokener jsonToken = new JSONTokener(new FileReader(fileName));
JSONObject jsonObject = new JSONObject(jsonToken);
//extract all base asset array
JSONArray symbols = jsonObject.getJSONArray("symbols");
Now I want to manipulate a dataset like this from a .json file
[
{
"symbol": "ETHBTC",
"priceChange": "-0.00029700"
},
{
"symbol": "LTCBTC",
"priceChange": "-0.00003300"
}
]
How do I import this data into my program as an array? I have looked for 8 hours, but could not find a solution. Thank you.
You are almost there, all you have to do is to new a JSON array from jsonToken as follows:
BTW, I think the JSON library you are using is org.json, not JSON.ORG. And both of your JSON strings are invalid, if no other JSON object exists behind comma, please remove it.
Code snippet
JSONTokener jsonToken = new JSONTokener(new FileReader(fileName));
JSONArray jsonArray = new JSONArray(jsonToken);
System.out.println(jsonArray.toString());
System.out.println(jsonArray.get(0));
Console output
[{"priceChange":"-0.00029700","symbol":"ETHBTC"},{"priceChange":"-0.00003300","symbol":"LTCBTC"}]
{"priceChange":"-0.00029700","symbol":"ETHBTC"}
This question already has answers here:
How to parse JSON in Java
(36 answers)
Closed 3 years ago.
How to parse this json response using Java
{
"Name": {
"name_description": "NIL",
"date": "NIL"
},
"Age": {},
"City": {},
"SOAP": [
["content", "subtopic", "topic", "code"],
["I advised her to call 911, which he did.", "history of present illness", "subjective", "{}"]
]
}
You'd have to use an external library like json-simple
Read more about it here
Use a library called org.json, it is honestly the best java json library.
for example:
import org.json.JSONObject;
private static void createJSON(boolean prettyPrint) {
JSONObject tomJsonObj = new JSONObject();
tomJsonObj.put("name", "Tom");
tomJsonObj.put("birthday", "1940-02-10");
tomJsonObj.put("age", 76);
tomJsonObj.put("married", false);
// Cannot set null directly
tomJsonObj.put("car", JSONObject.NULL);
tomJsonObj.put("favorite_foods", new String[] { "cookie", "fish", "chips" });
// {"id": 100001, "nationality", "American"}
JSONObject passportJsonObj = new JSONObject();
passportJsonObj.put("id", 100001);
passportJsonObj.put("nationality", "American");
// Value of a key is a JSONObject
tomJsonObj.put("passport", passportJsonObj);
if (prettyPrint) {
// With four indent spaces
System.out.println(tomJsonObj.toString(4));
} else {
System.out.println(tomJsonObj.toString());
}
}
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");
I hope someone can show me where i'm doing it wrong...
I'm using sendgrid for my email tracking and it is posting a JSON like the following:
[
{
"email": "john.doe#sendgrid.com",
"timestamp": 1337966815,
"event": "click",
"url": "http://sendgrid.com"
"userid": "1123",
"template": "welcome"
}
]
Now i want to get the value of for example for "timestamp" which is 1337966815 . I've tried the following:
StringBuffer jb = new StringBuffer();
String line = null;
try {
BufferedReader reader = req.getReader();
while ((line = reader.readLine()) != null)
jb.append(line);
} catch (Exception e) { /*report an error*/ }
String jsonString = jb.toString();
Gson gson = new Gson();
JsonObject jsonObject = gson.fromJson(jsonString, JsonObject.class);
String timeStam = jsonObject.get(timestamp).toString();
The string of jsonString gives me the following which i think is in the right format:
[ { "email": "john.doe#sendgrid.com", "timestamp": 1337966815, "event": "click", "url": "http://sendgrid.com" "userid": "1123", "template": "welcome" }]
But i'm getting the following error at this line of code - JsonObject jsonObject = gson.fromJson(jsonString, JsonObject.class);
java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 52
What am I doing wrong? Is it the format of jsonString that is confusing the JsonObject?
Any help would be very much appreciated.
Kind regards
Francois
The JSON you show in both examples is invalid. There is a comma missing after "url":"http://sendgrid.com"
Ignoring that, the JSON you show is an array of JSON objects, not an object. This is what the [] denotes (correcting the missing comma):
[
{
"email": "john.doe#sendgrid.com",
"timestamp": 1337966815,
"event": "click",
"url": "http://sendgrid.com",
"userid": "1123",
"template": "welcome"
}
]
If you are not mapping this JSON to a Java POJO, then you would want to use Gson's JsonParser to parse your String to a JsonElement (Note you could even use it to parse directly from the Stream, but this if for how you have your code now).
JsonElement je = new JsonParser().parse(jsonString);
Now you have what's called a "parse tree". This JsonElement is the root. To access it as an array you're going to do:
JsonArray myArray = je.getAsJsonArray();
You only show this array containing one object, but let's say it could have more than one. By iterating through the array you can do:
for (JsonElement e : myArray)
{
// Access the element as a JsonObject
JsonObject jo = e.getAsJsonObject();
// Get the `timestamp` element from the object
// since it's a number, we get it as a JsonPrimitive
JsonPrimitive tsPrimitive = jo.getAsJsonPrimitive("timestamp");
// get the primitive as a Java long
long timestamp = tsPrimitive.getAsLong();
System.out.println("Timestamp: " + timestamp);
}
Realize that Gson primarily is meant for Object Relational Mapping where you want to take that JSON and have it converted to a Java object. This is actually a lot simpler:
public class ResponseObject {
public String email;
public long timestamp;
public String event;
public String url;
public String userid;
public String template;
}
Because you have array of these, you want to use a TypeToken and Type to indicate your JSON is a List of these ResponseObject objects:
Type myListType = new TypeToken<List<ResponseObject>>(){}.getType();
List<ResponseObject> myList = new Gson().fromJson(jsonString, myListType);
I'm trying to parse a json file using json simple library but I'm having some trouble getting the code to parse the json file. I've done some searching but every example's json file is formatted differently from the one I'm using. I'm able to query the full json file, but I can't get a specific piece of information from my json file and add it to a list (the list turns up empty).
The json file in question (this is a snippet of the original file for simplicity's sake):
{
"status": "ok",
"count": "2",
"data":{
"1":{
"country": "U.S.A.",
"name": "Jeremy",
"id": 1
},
"3":{
"country": "U.K.",
"name": "Dell",
"id": 3
}
}
}
The code I've tried using:
List<String> list = new ArrayList<String>();
String json = myJSONFile; // myJSONFile is a place holder for the location of the file.
JSONObject jsonObject = (JSONObject) JSONValue.parse(json);
JSONObject data = (JSONObject) jsonObject.get("data");
for (int x = 0; y > data.size(); y++)
{
JSONObject id = (JSONObject) data.get(y + "");
list.add((String) id.get("name");
}
// Used to show if the list is empty or not.
JOptionPane.showMessageDialog(null, list);
As pointed out in the comments, you JSON isn't a valid one. You can try parsing it here.
The correct JSON appears to be:
{
"status": "ok",
"count": "2",
"data": {
"1": {
"country": "U.S.A.",
"name": "Jeremy",
"id": 1
},
"3": {
"country": "U.K.",
"name": "Jeremy",
"id": 3
}
}
}
A couple of errors in your code:
1) You are trying to parse the JSON file location without reading it. You need to first read the file containing JSON string
List<String> list = new ArrayList<String>();
String json = "..\\json.txt";
JSONParser parser = new JSONParser();
Object parsed = parser.parse(new FileReader(json));
JSONObject jsonObject = (JSONObject) parsed;
2) Your loop doesn't make much sense. Here you want to try and iterate over the keys returned by your JSONObject represented by data
JSONObject data = (JSONObject) jsonObject.get("data");
Iterator<?> keys = data.keySet().iterator();
while (keys.hasNext()) {
if (data.get(keys.next()) instanceof JSONObject) {
JSONObject id = (JSONObject) data.get(keys.next());
list.add((String) id.get("name"));
System.out.println("Yo => " + (String) id.get("name"));
}
}
Here is the full working sample, modify per your need to make it more generic and best practices:
public static void main(String... args) {
try {
List<String> list = new ArrayList<String>();
String json = "..\\json.txt"; //Location of your json file
JSONParser parser = new JSONParser();
Object parsed = parser.parse(new FileReader(json));
JSONObject jsonObject = (JSONObject) parsed;
JSONObject data = (JSONObject) jsonObject.get("data");
Iterator<?> keys = data.keySet().iterator();
while (keys.hasNext()) {
if (data.get(keys.next()) instanceof JSONObject) {
JSONObject id = (JSONObject) data.get(keys.next());
list.add((String) id.get("name"));
System.out.println("Yo => " + (String) id.get("name"));
}
}
// Used to show if the list is empty or not.
JOptionPane.showMessageDialog(null, list);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Output: