Extract values from Json - java

I am using org.json.simple.JSon and I have a JSON Array of JSON objects like this:
{"longitude:":-1.0,"latitude:":1.0},
{"longitude:":1.0,"latitude:":1.0},
{"longitude:":1.0,"latitude:":-1.0},
{"longitude:":-1.0,"latitude:":-1.0}
I need to extract values for longitudes and latitudes in to a list like this
[-1.0,1.0]
[1.0,1.0]
Is there a way to do so using Json or using regex?

It's very simple. Just create JSONArray from JSON string and get the JSONObject at each index of JSONArray and get the desired values.
Note: enclose the string [...] to make it valid JSON string.
sample code:
String json = "[{\"longitude:\":-1.0,\"latitude:\":1.0},{\"longitude:\":1.0,\"latitude:\":1.0}]";
JSONArray jsonArray = new JSONArray(json);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
System.out.println("longitude:" + jsonObject.getDouble("longitude:"));
System.out.println("latitude:" + jsonObject.getDouble("latitude:"));
}
Valid JSON string: (Notice the colon : used in key as well)
[
{
"longitude:": -1,
"latitude:": 1
},
{
"longitude:": 1,
"latitude:": 1
}
]

Try something like this (uses json.simple like you need but note that there are other JSON Java libraries that might even be better):
import java.util.ArrayList;
import java.util.List;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
public class PrintJsonArray {
public static void main(String[] args) throws ParseException {
String s = "[{\"longitude:\":-1.0,\"latitude:\":1.0},{\"longitude:\":1.0,\"latitude:\":1.0},{\"longitude:\":1.0,\"latitude:\":-1.0},{\"longitude:\":-1.0,\"latitude:\":-1.0}]";
JSONArray array = (JSONArray) new JSONParser().parse(s);
List<String> l = new ArrayList<>();
for (int i = 0; i < array.size(); i++) {
JSONObject json = (JSONObject) array.get(i);
double longitude = (double) json.get("longitude:");
double latitude = (double) json.get("latitude:");
l.add("[" + longitude + "," + latitude + "]");
}
System.out.println(l);
}
}
Please note 2 things:
In order for the JSON you supplied to be a valid one you need to add '[' and ']' surrounding your JSON.
You have an ':' in the longitude/latitude attribute names - not sure that this is what you meant (but of course this is only cosmetic)...

^.*?(?=longitude:":).*?(-?\d+\.\d+).*?(?=latitude:":).*?(-?\d+\.\d+).*$
Try this.This will give you all the values.
See demo.
http://regex101.com/r/sM9gJ5/1

Related

Accessing Nested Elements of JSON in Java

I have a java project in which I take a JSON and read its contents. I'm using org.json libraries and I would like to iterate through JSONObjects which are nested in a JSONArray, which is nested in a JSONObject. I keep getting this error though: JSONArray initial value should be a string or collection or array. I'm specifically getting the JSON from a web source, but here is an example of one: http://jsonblob.com/1062033947625799680
I'm particularly concerned about the fact that each player profile is unnamed, but there may be a simple fix for that.
I'd like to get access to each player profile and here is what I have that is causing an error:
import org.json.*;
JSONObject JSON = new JSONObject(content1.toString());
JSONArray data = new JSONArray(JSON.getJSONArray("data"));
for(int z = 1; i<data.length(); i++)
{
JSONObject ply = new JSONObject(data.getJSONObject(z));
System.out.println(ply.toString());
}
I have a feeling I just don't fully understand the terminology of JSON and/or the library that I'm using, but any help is appreciated.
Try this instead:
JSONObject JSON = new JSONObject(content1.toString());
JSONArray data = new JSONArray(JSON.getJSONArray("data"));
for(int i = 0; i<data.length(); i++) {
JSONObject ply = data.getJSONObject(i);
System.out.println(ply.toString());
}
It turns out I just have to access the particular element in one line:
JSONObject JSON = new JSONObject(content1.toString());
JSONArray data = JSON.getJSONArray("data");
for(int z = 0; z<data.length(); z++)
{
//JSONObject ply = new JSONObject(data.getJSONObject(z));
String name = data.getJSONObject(z).getString("skaterFullName");
System.out.println(name);
}

How to check if a key name contains a number/special character for a nested json object without looping keys?

I'm trying to check whether a JSON object contains a number/special character in its name, and the JSON object is an array of objects and each object itself a nested JSON object and also some keys has an array of objects.
My scenario is if my JSON object contains a number in its key name, that's an error record so I have to remove or skip those kinds of JSON Object, how can I do.
In Talend, If I have JSON object like following it will throw an error that please provide well-formatted JSON
[{"abc":"abcd"},{"def":"abcd"},{"0":"saran"}]
Since it has 0 as key talend throws that error.
The following is my Actual JSON object
[
{"_id":"5dd71ec4ad611b6464f912eb","dimensions":{"0":"0[object Object]","container":1,"weigth":2,"height":253,"lenght":600,"width":400},"errorLocation":{"location":{"type":"Point","geometry":[]},"addressLines":[],"geocodeScore":0,"cleanScore":0},"execution":{"timer":{"timestamps":[]}}},
{"_id":"5ddb15c42fef196f91d279b1","dimensions":{"container":1,"weigth":2,"height":253,"lenght":600,"width":400},"errorLocation":{"location":{"type":"Point","geometry":[]},"addressLines":[],"geocodeScore":0,"cleanScore":0},"execution":{"timer":{"timestamps":[]}}}
]
SO I have tried with JAVA routine
Here is my Java routine code
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.apache.commons.lang3.StringEscapeUtils;
import org.json.*;
public class Carrefour_Data_Remove_Issue {
/**
* helloExample: not return value, only print "hello" + message.
*
*
* {talendTypes} String
*
* {Category} User Defined
*
* {param} string("world") input: The string need to be printed.
*
* {example} helloExemple("world") # hello world !.
* #throws JSONException
*/
public static String jsonInput(String message) throws JSONException {
//String escapedString = StringEscapeUtils.unescapeJava(message);
//message = message.trim();
JSONArray jsonArray = new JSONArray(message);
JSONArray jsonArrayOutput = new JSONArray();
for (int i = 0, size = jsonArray.length(); i < size; i++)
{
JSONObject objectInArray = jsonArray.getJSONObject(i);
//message = objectInArray.toString();
//System.out.println(isJSONValid(message));
JSONObject innerObject = objectInArray.getJSONObject("dimensions");
if(innerObject.has("0")==false)
{
jsonArrayOutput.put(objectInArray);
}
//System.out.println(innerObject);
}
//System.out.println(jsonArrayOutput);
message = jsonArrayOutput.toString();
return message;
}
public static boolean isJSONValid(String test) {
try {
new JSONObject(test);
} catch (JSONException ex) {
return false;
// edited, to include #Arthur's comment
// e.g. in case JSONArray is valid as well...
}
return true;
}
}
You can try something like
String jsonString = innerObject.toString();
boolean b = jsonString.matches(".*\"(.*\\W+.*)\":.*");
// if (b) smth
// else smth else
This regex matches strings with a special character or number which are preceeded by " and followed by ":

Reading JSON from Java

I have this JSON structure:
{"metrics":[{
"type": "sum",
"column": ["rsales", "nsales"]
},
{
"type":"count",
"column":["ptype", "plan"]
}]
}
I am trying to read that JSON from Java and want to the output to be like:
str_sum="Sum"
str_sum_array[]= {"rsales" ,"nsales"}
str_count="count"
str_count_array[]= {"ptype" ,"plan"}
Here is my code so far:
JSONArray jsonArray_Metric = (JSONArray) queryType.get("metrics");
for (int i = 0; i < jsonArray_Metric.length(); i++) {
JSONObject json_Metric = jsonArray_Metric.getJSONObject(i);
Iterator<String> keys_Metrict = json_Metric.keys();
while (keys_Metrict.hasNext()) {
String key_Metric = keys_Metrict.next();
// plz help
}
}
How can I complete the code to produce the desired output?
Instead of using iterator you can use simple for-loop as below ..
JSONParser parser = new JSONParser();
JSONObject object = (JSONObject) parser.parse(queryType);
JSONArray jsonArray_Metric = (JSONArray) object.get("metrics");
for (int index = 0; index < jsonArray_Metric.size(); index++) {
JSONObject item = (JSONObject) jsonArray_Metric.get(index);
String type = (String) item.get("type");
JSONArray column = (JSONArray) item.get("column");
System.out.println("str_sum store=\"" + type + "\"");
System.out.println("str_count_array[] store=" + column);
}
Sample Run
str_sum store="sum"
str_count_array[] store=["rsales","nsales"]
str_sum store="count"
str_count_array[] store=["ptype","plan"]
If you want JSONArray to be displayed with curly braces instead of default (actual) braces i.e. square braces then you could so something like this while printing or you can even delete them by replacing them with empty string "".
System.out.println("str_count_array[] store " + column.toString().replace("[", "{").replace("]", "}"));
You can format your display code as you like by playing around with println statement.

how to parse arrays with direct values, twice json encoded

How can i parse an array with direct values , twice json encoded in Java, i get the data as a string and i want to get each value from the multidimensional array.
I'm kind of a noob regarding java, i managed to pull a not so elegant solution that encounters problems when i split by "," if the text inside has "," i could do it with regex but there must be a more elegant solution than this:
content = the data fetched from the api as a string
content = content.replace("\"[[", "[");
content = content.replace("]]\"", "]");
content = content.replaceAll("\\\\","");
for (String FaData : content.split("\\],\\[")) {
for (String FaDataData : FaData.split(",")) {
FaDataData.toString();
}
}
Here you have an example of how content string actually looks like when is fetched:
"[[308576,1410880665,162506,\"Bobcat\",1,\"http:\\\/\\\/hugelolcdn.com\\\/i460\\\/308576.jpg\",\"Well no\",82,3,\"\"],[308592,1410883832,9479,\"undeathkiller\",2,\"http:\\\/\\\/hugelolcdn.com\\\/i\\\/308592.gif\",\"Guess the stupidity level\",89,9,\"\"],[308574,1410879991,32277,\"rady123lol\",2,\"http:\\\/\\\/hugelolcdn.com\\\/i\\\/308574.gif\",\"force of habit\",92,3,\"\"],[308624,1410897686,149704,\"Raptide7\",1,\"http:\\\/\\\/hugelolcdn.com\\\/i460\\\/308624.jpg\",\"*breathing intensifies*\",114,8,\"\"],[308648,1410911037,114669,\"Huller\",1,\"http:\\\/\\\/hugelolcdn.com\\\/i460\\\/308648.jpg\",\"SPOILERS: Stannis kills Dumbledore\",133,2,\"\"],[308628,1410898654,135315,\"Mig_L\",1,\"http:\\\/\\\/hugelolcdn.com\\\/i460\\\/308628.jpg\",\"So badass\",117,2,\"gold\"],[308639,1410902872,62886,\"burningowl\",1,\"http:\\\/\\\/hugelolcdn.com\\\/i460\\\/308639.jpg\",\"Kid's going places yo\",125,4,\"\"],[308520,1410858123,73400,\"koppie888\",1,\"http:\\\/\\\/hugelolcdn.com\\\/i460\\\/308520.jpg\",\"4chan, what a beautifull place\",99,7,\"\"],[308546,1410872801,32277,\"rady123lol\",1,\"http:\\\/\\\/hugelolcdn.com\\\/i460\\\/308546.jpg\",\"( \\u0361\\u00b0 \\u035c\\u0296 \\u0361\\u00b0)\",118,17,\"\"],[308486,1410846601,176339,\"AtLeastISubmit\",1,\"http:\\\/\\\/hugelolcdn.com\\\/i460\\\/308486.jpg\",\"That 70's show called it.\",101,3,\"\"]]"
Assuming that you have your text in a String variable called everything, using the JSONSimple package, you can use the following code:
try {
// create a new JSONParser
JSONParser parser=new JSONParser();
// first JSON decoding
Object obj = parser.parse(everything);
// second JSON decoding
obj = parser.parse(obj.toString());
// cast the parsed JSON string to a new JSONArray
JSONArray array = (JSONArray)obj;
// loop through each line of the initial JSONArray
for (int i = 0; i < array.size(); i++){
// write the array values as a single line
System.out.println(i + " : " + array.get(i));
// parsing each line as a new JSONArray
JSONArray tmp = (JSONArray)parser.parse(array.get(i).toString());
for (int j = 0; j < tmp.size(); j++){ // iterate over the parsed values
System.out.println(i+"."+j+" : "+tmp.get(j));
}
}
} catch (ParseException ex) {
Logger.getLogger(Test1.class.getName()).log(Level.SEVERE, null, ex);
}
Of course, you also have to import the following classes from the JSON package :
import org.json.simple.JSONArray;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
Try this
content = content.trim();
content = content.substring(0, content.length()); //gets the length of content string
content = content.replaceAll("\\/","/"); //Replaces all \/ to /
It would apply to the brackets as well.
If you're using JSON then I would suggest using a JSON library such as jackson.
ObjectMapper mapper = new ObjectMapper();
String[][] 2Darray = mapper.readValue(content, String[][].class);
But then, if you are using JSON it would be nice if the format of your data was more structured. Obviously, that depends on whether or not you have any control over the API.

Parse Json In Java How to read Inner Value

Very New with Java Development Parsing JSON in JAVA Here is my Code.
package com.zenga.control;
import java.io.BufferedReader;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.GetMethod;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JSONSerializer;
public class Start {
public String readUrl(String urlString) {
String jsonString = null;
try {
HttpClient client = new HttpClient();
GetMethod get = new GetMethod(urlString);
client.executeMethod(get);
jsonString = get.getResponseBodyAsString();
}catch(Exception e) {
}
return jsonString;
}
public void getAddAsBeanObject() {
try {
String jsonString = new Start().readUrl("http://myDomain/JsonZ.json");
JSONObject obj = (JSONObject) JSONSerializer.toJSON(jsonString);
System.out.println(obj);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
new Start().getAddAsBeanObject();
}
}
As I successfully Read Value in JSONObject and it also showing all JSON String on console But How can i Get Value For ID and UID and DURATION ?
Here The JSONString the i read in System.out.println(obj);
{
"Demo": {
"CONTENT": [
{
"ID": " 283 ",
"UID": " 87897bc8-ae9b-11e1-bdcf-123141042154 ",
"DURATION": "Full"
},
{
"ID": " 283 ",
"UID": " 87897bc8-ae9b-11e1-bdcf-123141042154 ",
"DURATION": "Full"
}
]
}
}
Following code can be used to iterate the JSON objects inside the JSON array 'CONTENT', using .get(java.lang.String) as documented, to pull the value out of the JSONObject.
I have only demonstrated how to get the ID but the same logic applies to the other values.
JSONObject obj = (JSONObject) JSONSerializer.toJSON(jsonString);
JSONArray content = obj.getJSONObject("Demo").getJSONArray("CONTENT");
java.util.Iterator<?> iterator = content.iterator();
while (iterator.hasNext()) {
JSONObject o = (JSONObject) iterator.next();
System.out.println(o);
System.out.println(o.get("ID"));
// etc...
}
Following is a sample code to reach the array`s inner objects specific to pattern you have provided.
String str = "{"+
"\"Demo\": {"+
"\"CONTENT\": ["+
" {"+
"\"ID\": \" 283 \","+
"\"UID\": \" 87897bc8-ae9b-11e1-bdcf-123141042154 \","+
"\"DURATION\": \"Full\""+
" },"+
"{"+
"\"ID\": \" 283 \","+
"\"UID\": \" 87897bc8-ae9b-11e1-bdcf-123141042154 \","+
"\"DURATION\": \"Full\""+
" }"+
"]"+
"}"+
"}";
try {
JSONObject jsr = new JSONObject(str); // JSON object with above data
JSONObject demo = jsr.getJSONObject("Demo"); // get Demo which is a JSON object inside jsr.
JSONArray content = demo.getJSONArray("CONTENT");// get CONTENT which is Json array inside Demo
for (int i = 0; i < content.length(); i++) { // iterate over array to get inner JSON objects and extract values inside
JSONObject record = content.getJSONObject(i); // each item of Array is a JSON object
String ID = record.getString("ID");
String UID = record.getString("UID");
String DURATION = record.getString("DURATION");
}
}
catch (JSONException e) {
e.printStackTrace();
}
Note: Above code is specifc to org.Json API. Find appropriate methods in library you are using for Json handling
Use a loop that iterates through the Json Object and access each of the element
for(/**loop until the counter reaches the size of the json object**/) {
//Access each element based on the ID as below.
System.out.println(Demo.CONTENT[CurrentCounter].ID); //here CurrentCounter is index
System.out.println(Demo.CONTENT[CurrentCounter].UID); ..... //read through all ids
}
I guess you could use the 'get' Method on the JSONObject. If you don't know which key to look for, I suggest using a Method that returns all available keys, like the one called 'keys'. With these values, you could then traverse down in you structure. See here:
http://json-lib.sourceforge.net/apidocs/net/sf/json/JSONObject.html
I guess GSON will be a big help for you.
See here Parsing json object into a string
There is a samplecode as well
Create a class which have variables you want to read from json string.And Gson will handle the rest.
https://code.google.com/p/google-gson/
Example usage:
//convert the json string back to object
DataObject obj = gson.fromJson(br, DataObject.class);

Categories