I currently have this JSON:
[
{
"example": "12345678",
"test": "0",
"name": "tom",
"testdata": "",
"testtime": 1531209885613
},
{
"example": "12634346",
"test": "43223452234",
"name": "jerry",
"testdata": "pawenkls",
"testtime": 1531209888196
}
]
I am trying to parse through the array to find a value of "testdata" that matches the value of "testdata" that I have generated, which I am currently doing like so:
JsonArray entries = (JsonArray) new JsonParser().parse(blockchainJson);
JsonElement dataHash = ((JsonObject)entries.get(i)).get("dataHash");
Then I wish to find the value of "example" that is in the same array as the "testdata" with the value "pawenkls".
How do I search for the "example" value that is in the same group as the value of "test data" that I have found?
You need to run through the objects in the array and check the value of the testData field against yours. Then read its example field.
String testData = "pawenkls";
JsonArray entries = (JsonArray) new JsonParser().parse(blockchainJson);
String example = null;
for(JsonElement dataHashElement : entries) {
JsonObject currentObject = dataHashElement.getAsJsonObject();
if(testData.equals(currentObject.get("testdata").getAsString())) {
example = currentObject.get("example").getAsString();
break;
}
}
System.out.println("example: "+example);
This prints out
example: 12634346
Here is a Java 8 version doing the same thing:
String testData = "pawenkls";
JsonObject[] objects = new Gson().fromJson(blockchainJson, JsonObject[].class);
Optional<JsonObject> object = Arrays.stream(objects)
.filter(o -> testData.equals(o.get("testdata").getAsString()))
.findFirst();
String example = null;
if(object.isPresent())
example = object.get().get("example").getAsString();
System.out.println("example: "+example);
Related
**My result of JSONObject to convert as follows bellow code and have searched for many this how to convert using java but I converted that **
{
"result": {
"accountnames": [{
"accountName": "Hari",
"accountId": 878488
}, {
"accountName": "ravi",
"accountId": 878487
}],
"sales": [{
"accountSales": "89",
"accountId": 878488
}, {
"accountName": "98",
"accountId": 878487
}],
"countResult": [{
"accountResult": "945",
"accountId": 878488
}, {
"accountResult": "9452",
"accountId": 878489
}]
}
}
*and this is where the sample code to be converted *
{
"result": [{
"accountName": "Hari",
"accountSales": "89",
"accountResult": "945",
"accountId": 878488
},
{
"accountName": "ravi",
"accountSales": "98",
"accountId": 878487
},
{
"accountResult": "9452",
"accountId": 878489
}
]
}
My required JSON data has to be formatted as below
You need to group all the elements by accountId. You can use something like this depending on the json library that you are using.
Initialize the json object:
JSONObject rootJson = new JSONObject(json);
JSONObject resultJson = rootJson.getJSONObject("result");
Create a map to hold the objects by accountId:
Map<String, JSONObject> accountIds = new HashMap<>();
Then iterate for each key in the json, then for each element in the arrays and then for each property of the object inside the json:
Iterator mainKeys = resultJson.keys();
while (mainKeys.hasNext()) {
String key = (String) mainKeys.next();
JSONArray array = resultJson.getJSONArray(key);
for (int index = 0; index < array.length(); index++) {
JSONObject object = array.getJSONObject(index);
if (object.has("accountId")) {
String accountId = object.get("accountId").toString();
JSONObject accum = accountIds
.computeIfAbsent(accountId, (k) -> new JSONObject());
// depending on the json impl you can use putAll or similar
Iterator objKeys = object.keys();
while (objKeys.hasNext()) {
String property = (String) objKeys.next();
accum.put(property, object.get(property));
}
} else {
// does not have account id, ignore or throw
}
}
}
Finally create the json file and add the elements to the JSONArray:
JSONObject finalJson = new JSONObject();
finalJson.put("result", new JSONArray(accountIds.values()));
System.out.println(finalJson.toString());
(note: the json has an error in sales array accountName instead of accountSales)
I have a json (result) like the below , i need the value of Key "extra", that is "contact office".
I tried the below code, but it did not work, can you help?
JSONArray jsonArray = new JSONArray(result.toString().trim());
JSONObject json = jsonArray.getJSONObject(0).getJSONObject("student").getJSONArray("department").getJSONObject(0).getJSONObject("classes");
String val=json.getString("extra");
// JSON Example
{
"student": [
{
"department" : [
{
"classes" : [
{
"grade" : "A",
"fine" : "No"
},
{
"grade" : "B",
"fine" : "Yes",
"extra" : "contact office"
},
{
"grade" : "C",
"fine" : "NA"
}
],
}
],
}
],
}
You mixed up JSONArray and JSONObject a few times, not sure exactly what I had to change but the following will work:
JSONObject jsonObject = new JSONObject(result.toString().trim());
JSONArray jsonArray = jsonObject
.getJSONArray("student").getJSONObject(0).getJSONArray("department").getJSONObject(0)
.getJSONArray("classes");
String val = jsonArray.getJSONObject(1).getString("extra");
Is this a full sample? If so it doesn't start out as an array. Student is and object not an array. If it is just a sample of one item in the array then you're okay.
The second thing I noticed is: getJSONObject("classes"). Classes is an array not an object, this won't work.
Would you like to consider using JsonPath. You could do something like this -
String[] extraValues = JsonPath.read(json, "$.student[0].department[0].classes[*].extra");
Using Simple-JSON on the following JSON formatted file, I'm having a lot of trouble understanding how to access the objects within the array under "name".
JSON File:
[
{
"name":{
"firstName": "Developer",
"lastName": "D"
},
"id": 00,
"permissionLevel": 3,
"password": 12345
},
{
"name":{
"firstName": "Bob",
"lastName": "Smith"
},
"id": 01,
"permissionLevel": 2,
"password": 23456
}
]
I'm able to obtain the information for all of the other contents because they're not located in a nested array; However, when I attempt to retrieve the objects under "name", all that is output is the String found in the JSON file.
Current code:
String[] searchData = {
"name",
"firstName",
"lastName",
"id",
"permissionLevel",
"password"
};
jsonArray = (JSONArray)new JSONParser().parse(s);
for(int i = 0; i < jsonArray.size(); i++){
JSONObject jo = (JSONObject)jsonArray.get(i);
for(int j = 0; j < searchData.length; j++){
System.out.println(
searchData[j] + ": " + jo.get(searchData[j]));
}
}
Output:
name: [{"firstName":"Developer","lastName":"D"}]
firstName: null
lastName: null
id: 0
permissionLevel: 3
password: 12345
name: [{"firstName":"Bob","lastName":"Smith"}]
firstName: null
lastName: null
id: 1
permissionLevel: 2
password: 23456
As you can see, "name" outputs a String from the JSON file, and not each individual value.
In the end, I need to write a universal code that can accept new "searchData" tags for each file that's input.
Might someone be able to direct me how to obtain objects held
within nested arrays?
Or perhaps I need to use a different Library? If so, which one is the most efficient for Java? I'm not programming for Android, and I continue to find Library suggestions for Android, constantly.
My apologies if this post is a dupe, but no other posts are aiding me.
You should get your firstname and lastname, like:
jo.get("name").get("firstname");
jo.get("name").get("lastname");
To get the objects held within nested arrays/objects, you will have to write a recursive method and flatten the structure into a map. Below example shows the same:
public static void main(String args[]) throws ParseException {
Object object = new JSONParser().parse("[ { \"name\":{ \"firstName\": \"Developer\", \"lastName\": \"D\" }, \"id\": 00, \"permissionLevel\": 3, \"password\": 12345 }, { \"name\":{ \"firstName\": \"Bob\", \"lastName\": \"Smith\" }, \"id\":01, \"permissionLevel\": 2, \"password\": 23456 }]");
Map<String, Object> pairs = new HashMap<>();
addValues(object, pairs);
System.out.println(pairs);
}
public static void addValues(Object object, Map<String, Object> pairs){
if(object instanceof JSONObject){
JSONObject jsonObject = (JSONObject) object;
for(String key : jsonObject.keySet()){
if(jsonObject.get(key) instanceof JSONObject || jsonObject.get(key) instanceof JSONArray){
addValues(jsonObject.get(key), pairs);
}else{
pairs.put(key, jsonObject.get(key));
}
}
}else if(object instanceof JSONArray){
JSONArray jsonArray = (JSONArray)object;
for(Object element : jsonArray){
addValues(element, pairs);
}
}
}
You can tweak this method to have keys like name.firstname or name.lastname depending on requirements.
I understand that you want the searchData tags to be taken into consideration while parsing the JSON. I would suggest using Google Gson for this case.
You can write a POJO which return the ArrayList<User> for your JSON.
Refer this article on how use Google Gson
{
"Employee": [
{
"empMID": "mock:1",
"comments": [],
"col1": "something",
"contact": [{"address":"2400 waterview", "freetext":true}
],
"gender": "male"
},
{
"empMID": "mock:2",
"comments": [],
"col1": "something",
"contact": [{"address":"2200 waterview", "freetext":true}
],
"gender": "female"
}
],
"cola": false,
"colb": false
}
This is how my Json file looks .I m required to convert this json to a csv .(I m trying to convert a multi-dimesional data to 2d).I m using gson for my purpose.I cannot use gson.fromgson() function to object map with a template because it should be generic .
I know we can use CDL to convert jsonarray to csv format but It wont work in my case .
my csv format looks like
Employee*
empMID,comment.$,contact.address,contact.freetext,gender
mock:1,,2400 waterview,TRUE,male
mock:123,,2200 waterview,TRUE,female
colA#
TRUE
colB#
FALSE
I tried using google-GSON api to convert to this format .But I m not able to convert to this format .I have used * to represent its a json array and # to represent its a primitive type and contact.address to represent nested array inside another json array .I having problem relating this nested structure .I m able to traverse everything recursively like a column. Thanks in advance
public static void main(String[] args) throws IOException{
BufferedReader reader=null;
StringBuilder content=null;
String result=null;
reader = new BufferedReader(new FileReader("temp.json"));
String line = null;
content= new StringBuilder();
while ((line = reader.readLine()) != null) {
content.append(line);
}
reader.close();
result= content.toString();
JsonElement jelement = new JsonParser().parse(result);
printJsonRecursive(jelement);
}
public static void printJsonRecursive(JsonElement jelement){
if(jelement.isJsonPrimitive()){
System.out.println(jelement.getAsString());
return;
}
if(jelement.isJsonArray()){
JsonArray jarray= jelement.getAsJsonArray();
for(int i=0;i<jarray.size();i++){
JsonElement element= jarray.get(i);
printJsonRecursive(element);
}
return;
}
JsonObject jobject= jelement.getAsJsonObject();
Set<Entry<String, JsonElement>> set= jobject.entrySet();
for (Entry<String, JsonElement> s : set) {
printJsonRecursive(s.getValue());
}
}
}
You can achieve this thru reflection if you have a object mapped to the json.
use gson/jackson to convert json to java object
append fields using reflection by iterating the class and get any field you interested in.
append value with reflection by getting value from the target object.
More detail look at my blog post below:
vcfvct.wordpress.com/2015/06/30/converting-nested-json-files-to-csv-in-java-with-reflection/
You are not printing the key. This should fix it.
for (Entry<String, JsonElement> s : set) {
System.out.println(s.getKey()); //Added
printJsonRecursive(s.getValue());
}
You can take care of \ns from here.
EDIT
If you want to print the keys just once for repeating json objects, create a Java bean to hold the data and populate it during your recursion. Once the bean is complete, add a method there to print all the data in the format you want (printing keys only once and so on).
You can use the library json2flat for converting your JSON to CSV.
This library doesn't require any POJO's. It simply takes your JSON as string and returns a 2D representation of it in the format of List<Object[]>.
For example for the JSON:
{
"Employee": [
{
"empMID": "mock:1",
"comments": [],
"col1": "something",
"contact": [{"address":"2400 waterview", "freetext":true}
],
"gender": "male"
},
{
"empMID": "mock:2",
"comments": [],
"col1": "something",
"contact": [{"address":"2200 waterview", "freetext":true}
],
"gender": "female"
}
],
"cola": false,
"colb": false
}
It gives an output:
/cola,/colb,/Employee/empMID,/Employee/col1,/Employee/gender,/Employee/contact/address,/Employee/contact/freetext
,,"mock:1","something",,"2400 waterview",true
,,"mock:2","something",,"2200 waterview",true
false,false,,,,,
/**
* Get separated comlumns used a separator (comma, semi column, tab).
*
* #param headers The CSV headers
* #param map Map of key-value pairs contains the header and the value
*
* #return a string composed of columns separated by a specific separator.
*/
private static String getSeperatedColumns(Set<String> headers, Map<String, String> map, String separator) {
List<String> items = new ArrayList<String>();
for (String header : headers) {
String value = map.get(header) == null ? "" : map.get(header).replaceAll("[\\,\\;\\r\\n\\t\\s]+", " ");
items.add(value);
}
return StringUtils.join(items.toArray(), separator);
}
I have a JSON file which contains an array of item objects:
{
"item": [
{
"title": "TitleA",
"link": "http://www.abc.html?partner=rss&emc=rss",
"guid": {
"-isPermaLink": "true",
"#text": "www.abc.html"
},
"atom:link": {
"-rel": "standout",
"-href": "http://www.abc.html?partner=rss&emc=rss"
},
"media:content": {
"-url": "standard.jpg",
"-medium": "image",
"-height": "75",
"-width": "75"
},
"media:description": "This is the description.",
"media:credit": "Reuters",
"description": "In depth description",
"dc:creator": "By test creator",
"pubDate": "Sun, 21 Oct 2012 11:29:12 GMT",
"category": "World"
},
{
"title": "TitleB",
"link": "http://www.abc.html?partner=rss&emc=rss",
"guid": {
"-isPermaLink": "true",
"#text": "www.abc.html"
},
"atom:link": {
"-rel": "standout",
"-href": "http://www.abc.html?partner=rss&emc=rss"
},
"media:content": {
"-url": "standard.jpg",
"-medium": "image",
"-height": "75",
"-width": "75"
},
"media:description": "This is the description.",
"media:credit": "Reuters",
"description": "In depth description",
"dc:creator": "By test creator",
"pubDate": "Sun, 21 Oct 2012 11:29:12 GMT",
"category": "World"
}
]
}
Now I know how to get the "title", but I don't know how I would access the "-url" within "media:content" for example, since it seems to be a JSON object within the Item object. How would I get this value and assign it to a value in my Item class?
try as to get "-url" within "media:content" from current json string :
JSONObject jsonObject = new JSONObject("Your JSON STRING HERE");
JSONArray jsonArray =jsonObject.getJSONArray("item");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObjectitem=
jsonArray.getJSONObject(i);
// get title or link here
String strtitle=jsonObjectitem.getString("title");
//....get other values in same way
// get media:content json object
JSONObject jsonObjectmediacontent =
jsonObjectitem.getJSONObject("media:content");
// get url,medium,...
String strurl=jsonObjectmediacontent.getString("-url");
//....get other values in same way
}
Write below code to parse -url string, it will solve your problem.
JSONObject mMainJsonObj = new JSONObject("Pass Json Response String Here");
JSONArray mItemJsonArray = mMainJsonObj.getJSONArray("item");
for (int i = 0; i < mItemJsonArray.length(); i++) {
JSONObject mJsonObj1 = mItemJsonArray.getJSONObject(i);
String mTitle = mJsonObj1.getString("title");
String mLink = mJsonObj1.getString("link");
JSONObject mJsonObjGuid = mJsonObj1.getJSONObject("guid");
String mIsPermLink = mJsonObjGuid.getString("-isPermaLink");
String mText = mJsonObjGuid.getString("#text");
JSONObject mJsonObjAtomLink = mJsonObj1.getJSONObject("atom:link");
String mRel = mJsonObjAtomLink.getString("-rel");
String mHref = mJsonObjAtomLink.getString("-href");
JSONObject mJsonObjMediaContent = mJsonObj1.getJSONObject("media:content");
String mUrl = mJsonObjMediaContent.getString("-url");
String mMedium = mJsonObjMediaContent.getString("-medium");
String mHeight = mJsonObjMediaContent.getString("-height");
String mWidth = mJsonObjMediaContent.getString("-width");
}
And see below link for more information.
Json Parsing Example
Solution with Jackson: read your JSON into a JsonNode using an ObjectMapper and retrieve your values like this:
// Since JsonNode implements Iterable of itself and cycles through array elements,
// this works
for (final JsonNode element: node)
doSomethingWith(element.get("media:content").get("-url"));