For the below Json payload I'am trying to get the first array element of email_address.
However using the below code I get email address but with the array bracket and quotes like: ["test#test.com"].
I need only the email address text. First element array.
Payload:
{
"valid":{
"email_addresses":[
"testauto#test.com"
]
}
}
Code:
JSONParser parser = new JSONParser();
JSONObject jsonObject = (JSONObject) parser.parse(new FileReader(jsonfilepath));
JSONObject jsonObjects = (JSONObject) parser.parse(jsonObject.get("valid").toString());
String email = jsonObjects.get("email_addresses").toString();
System.out.println("Email address:"+email);
Maybe this unitTest could help you
#Test
public void test() throws JSONException, FileNotFoundException {
JSONObject json = new JSONObject(new JSONTokener(new FileInputStream(new File(jsonfilepath))));
JSONObject valid = (JSONObject) json.get("valid");
Object emailAdresses = valid.get("email_addresses");
if (emailAdresses instanceof JSONArray) {
JSONArray emailAdressArray = (JSONArray) emailAdresses;
Object firstEmailAdress = emailAdressArray.get(0);
System.out.println(firstEmailAdress.toString());
}
}
You could use JSONArray to get the array values:
JSONArray emailAddresses = (JSONArray) jsonObjects.get("email_addresses");
String email = emailAddresses.getJSONObject(0).toString()
System.out.println("Email address: " + email);
Even though I strongly encourage using gson to parse json instead of doing this way, it makes life easier.
Related
Example of my json file is
{
"collection": [
{
"trophy-name": {
"text": "swimming",
"text2": "fast swimming"
},
"length": "50m",
"pool": "outside",
"weather": "20"
}
]
}
Right now I am able to get values from lenght, pool and weather. But I am stuck on how to access the nested array nested object trophy-name.
My code is:
public class main {
public static void main(String[] args) throws FileNotFoundException, IOException, ParseException
{
JSONParser parser = new JSONParser();
Object obj = parser.parse(new FileReader("...")); // json path
JSONObject jsonObject = (JSONObject) obj;
JSONArray array = (JSONArray) jsonObject.get("collection");
for (Object number : array )
{
JSONObject testObj = (JSONObject) number;
String pool = (String)testObj.get("pool");
System.out.println(testObj.get("length"));
System.out.println(pool);
System.out.println(testObj.get("weather"));
}
}
}
This is my first time experimenting with json files so I am trying to play around with it so the code is not great.
I probably have to create new object like
JSONObject trophyObj = (JSONObject) jsonObject.get("trophy-name");
And then from there I should be able to get the text with this?
String troph = (String) trophyObj.get("text");
Even if I that is correct I am not sure how to implement it into the loop or if there is better way to do the loop?
Dont mind redoing the code differently and any advice appreciated.
Yes, you are right, simply extract the JSONObject within the loop and then get the required fields.
public class main {
public static void main(String[] args) throws FileNotFoundException, IOException, ParseException
{
JSONParser parser = new JSONParser();
Object obj = parser.parse(new FileReader("...")); // json path
JSONObject jsonObject = (JSONObject) obj;
JSONArray array = (JSONArray) jsonObject.get("collection");
for (Object number : array )
{
JSONObject testObj = (JSONObject) number;
String pool = (String)testObj.get("pool");
System.out.println(testObj.get("length"));
System.out.println(pool);
System.out.println(testObj.get("weather"));
JSONObject trophyObj = (JSONObject) testObj.get("trophy-name");
System.out.println((String)trophyObj.get("text"));
System.out.println((String)trophyObj.get("text2"));
}
}
}
I am returning an JSON array which contains many objects, I'm looking to be able to search the attributes in each object and then return the objects that meet this criteria.
I am able to return the JSON array but I'm having trouble on how to then search through the objects to match the attribute values to a given value.
Some example values from the array:
[
{"blobJson":"x","deviceMfg":10,"eventCode":0,"sensorClass":3,"sensorUUID":"136199","timeStamp":1.483384640123117E9,"uID":"136199_3_10"},
{"blobJson":"x","deviceMfg":10,"eventCode":0,"sensorClass":3,"sensorUUID":"136199","timeStamp":1.483379834470379E9,"uID":"136199_3_10"},
{"blobJson":"x","deviceMfg":10,"eventCode":0,"sensorClass":3,"sensorUUID":"136199","timeStamp":1.483384639621985E9,"uID":"136199_3_10"}
]
I'm using the following code to return the array, which works as expected:
JsonParser jp = new JsonParser();
JsonElement root = jp.parse(new InputStreamReader((InputStream) request.getContent()));
JsonArray rootArr = root.getAsJsonArray();
The following block of code is what I'm using to search through an object for the given attribute value, this code works when only an object is returned but gives an error when the whole array is returned:
JsonObject rootObj = rootArr.getAsJsonObject();
for (String attribute : attributes) {
System.out.println(rootObj.get(attribute).getAsString());
}
It is giving the error:
java.lang.IllegalStateException: Not a JSON Object:
I've tried changing rootObj.get(attribute) to rootArr.get(attribute) but that returns the error:
incompatible types: java.lang.String cannot be converted to int
This is the method call:
method("136199", Arrays.asList("blobJson", "deviceMfg", "uID"));
Method declaration:
void method(String sensor, List<String> attributes)
The issue is that you're trying to treat JsonArray to JsonObject. Try the below code and see if it works for you. Point of interest for now is - JsonObject rootObj = rootArr.get(0).getAsJsonObject();
public static void main(String[] args) {
String json = "[{\"blobJson\":\"x\",\"deviceMfg\":10,\"eventCode\":0,\"sensorClass\":3,\"sensorUUID\":\"136199\",\"timeStamp\":1.483384640123117E9,\"uID\":\"136199_3_10\"},{\"blobJson\":\"x\",\"deviceMfg\":10,\"eventCode\":0,\"sensorClass\":3,\"sensorUUID\":\"136199\",\"timeStamp\":1.483379834470379E9,\"uID\":\"136199_3_10\"},{\"blobJson\":\"x\",\"deviceMfg\":10,\"eventCode\":0,\"sensorClass\":3,\"sensorUUID\":\"136199\",\"timeStamp\":1.483384639621985E9,\"uID\":\"136199_3_10\"}]";
JsonParser jp = new JsonParser();
JsonElement root = jp.parse(json);
JsonArray rootArr = root.getAsJsonArray();
JsonObject rootObj = rootArr.get(0).getAsJsonObject();
rootObj.entrySet().forEach(entry -> System.out.println(entry.getKey()+": "+entry.getValue().getAsString()));
}
Here is what you can try
try {
JSONArray jsonArray = new JSONArray(data);
for (int i = 0; i < jsonArray.length(); i++) {
Log.e("JSON Count", jsonArray.get(i).toString());
}
} catch (Exception e) {
}
I'm trying to use JSON simple as part of a Java application to pull specific data from a .json file. Whenever I run the program, I get an unexpected token error message when it tries to parse.
A simplified version of the JSON file is as follows:
{"id":123,"text":"sample1","user":{"id":111,"name":"username"},"lang":"en"}
{"id":345,"text":"sample2","user":{"id":555,"name":"user2"},"lang":"en"}
My code is as follows:
public static void readJSON() {
JSONParser jsonParser = new JSONParser();
try {
FileReader reader = new FileReader(fileLocation);
JSONObject jsonObject = (JSONObject) jsonParser.parse(reader);
JSONArray jsonArray = (JSONArray) jsonObject.get("");
Iterator<?> i = jsonArray.iterator();
while (i.hasNext()) {
JSONObject obj = (JSONObject) i.next();
int tweetID = (int) obj.get("id");
String lang = (String) obj.get("lang");
}
} catch (Exception e) {
e.printStackTrace();
}
}
In this example, the line of code:
JSONObject jsonObject = (JSONObject) jsonParser.parse(reader);
throws an error due to an unexpected token at the first left brace ({) of the second JSON object (i.e, at the brace before "id":345).
How could I go about resolving this issue?
And, as a follow up, how would one also pull the information for the username in this example?
Thanks for taking the time to read through this, and for any assistance provided!
That file is an invalid JSON file, it contains an entire object on each line.
What you'll need to do is read the file line by line, and then passing each line to the parser to create a new object.
If you fix your code, you can solve unexpected token error.
public static void readJSON() {
JSONParser jsonParser = new JSONParser();
try {
FileReader reader = new FileReader(fileLocation);
//You need to fix this part
JSONArray jsonArray = (JSONArray) jsonParser.parse(reader);
Iterator<?> i = jsonArray.iterator();
while (i.hasNext()) {
JSONObject obj = (JSONObject) i.next();
int tweetID = (int) obj.get("id");
String lang = (String) obj.get("lang");
}
} catch (Exception e) {
e.printStackTrace();
}
}
You are trying to parse JSON object, and you actually have two JSON objects.
And in your code you are actually expect an array of JSON objects.
So, use the proper JSON array:
[
{"id":123,"text":"sample1","user":{"id":111,"name":"username"},"lang":"en"},
{"id":345,"text":"sample2","user":{"id":555,"name":"user2"},"lang":"en"}
]
In order to quickly check your JSON syntax, you can use some online tool.
Your JSON is indeed wrong. It actually contains 2 valid JSONs. If you want to create one valid JSON document you have to wrap your input with { and } or [ ] if this is an array or collection. Please note the comma that separates 2 different entities.
[
{"id":123,"text":"sample1","user":{"id":111,"name":"username"},"lang":"en"},
{"id":345,"text":"sample2","user":{"id":555,"name":"user2"},"lang":"en"}
]
I want to read this json in a servlet
{
"text" : "ABC",
"msg" : "9551667858",
"all":[
{"name":"one"},
{"name":"two"}
],
"obj":{
"firstname":"John",
"lastname":"Doe"
}
}
Now i want to get this values to separately to string,jsonarray and json object
this is how i do that
PrintWriter out = response.getWriter();
try {
String newObj = request.getParameter("text");;
JSONObject jObj = new JSONObject(request.getParameter("obj"));
JSONArray jArray=new JSONArray(request.getParameter("all"));
out.print(newObj);
} catch (Exception e) {
e.printStackTrace();
out.write(e.toString());
}
response.setContentType("application/json");
your code is partially correct.String newObj = request.getParameter("jsondata"); is correct. Then you have to create the jObj from newObj string.
String jsonString = <your json String>
JSONObject jsonObj = new JSONObject(jsonString);
JSONObject allObj = jsonObj.getJSONObject("obj");
JSONArray allArray = jsonObj.getJSONArray("all");
First read the data from request object :-
String jsonStr = request.getParameter("jsondata");
Use org.json library to parse it and create JsonObject :-
JSONObject jsonObj = new JSONObject(jsonStr );
Now, use this object to get your values :-
String id = jsonObj.getString("text");
You can see complete example here :-
How to parse Json in java
if your String data like ,
{
"text" : "ABC",
"msg" : "9551667858",
"all":[
{"name":"one"},
{"name":"two"}
],
"obj":{
"firstname":"John",
"lastname":"Doe"
}
}
and It can get like,
String jsonData = request.getParameter("jsondata");
Parse to JSONObject is.
JSONObject jsonObject = new JSONObject(jsonData); // put "String"
You can get JSONArray like,
JSONArray jsonArray = jsonObject.getJSONArray("all");
good luck
I want to use json encoded array which i am return from this link :
http://sids.roundone.asia/suggest.json?data=soft
as suggestions in android application.
(I have used json_encode($arr) function in php file and i am returning that as response for above link)
I have a problem in reading this response in java and storing it in an ArrayList.
My code is :
try {
String temp=sName.replace(" ", "%20");
URL js = new URL("https://sids.roundone.asia/suggest.json?data="+temp);
URLConnection jc = js.openConnection();
BufferedReader reader = new BufferedReader(new InputStreamReader(jc.getInputStream()));
String line = reader.readLine();
JSONObject jsonResponse = new JSONObject(line);
JSONArray jsonArray = jsonResponse.getJSONArray("results");
for(int i = 0; i < jsonResponse.length(); i++){
JSONObject r = jsonArray.getJSONObject(i);
ListData.add(new SuggestGetSet(jsonResponse.get(String.vlaueOf(iss)));
}
}
As I could see on your link, you're returning a JSON Array, instead of a JSON Object, ( "[ ]" instead of "{ }") and then in your java code you're trying to create a JSONObject here:
JSONObject jsonResponse = new JSONObject(line);
Try changing that to:
JSONArray jsonResponse = new JSONArray(line);
You return JSON array directly not a JSON Object have inner array so cast your incoming response to JSONArray directly.
JSONArray jsonResponse = new JSONArray(line);