Retrieve just one field from JSON string in Java - java

Is there a way to just one field from the JSON string? My code is as follows:
Object obj = parser.parse(resp);
System.out.println(obj);
JSONArray array = new JSONArray();
array.add(obj);
JSONObject obj2 = (JSONObject)array.get(0); //Getting NPE here
//Object obj3 = obj2.get("data");
System.out.println("Data: " + obj2.get("data"));
//System.out.println("Email: " + obj3.get("email_address"));
I'm using the following libraries
import org.json.simple.JSONObject;
import org.json.simple.JSONArray;
import org.json.simple.parser.ParseException;
import org.json.simple.parser.JSONParser;
From the response string resp, I just need data.email_address. I am unable to find a way to do it.

So if this is your input:
{
"data": {
"email_address": "example#example.com"
}
}
You first will need to make it a JSONObject:
JSONObject object = (JSONObject) new JSONParser().parse(json);
And then you can get data, another JSONObject:
JSONObject data = (JSONObject) object.get("data")
And from your data Object you can get email_address:
String email = data.get("email_address").toString();
If your input is an array of users, like this:
{
"users": [
{
"data": {
"email_address": "example#example.com"
}
},
{
"data": {
"email_address": "exapmle2#example2.com"
}
}
]
}
You can get it the same way:
JSONObject object = (JSONObject) new JSONParser().parse(json);
JSONArray users = (JSONArray) object.get("users");
JSONObject user0 = (JSONObject) users.get(0);
JSONObject user0data = (JSONObject) user0.get("data");
String email = user0data.get("email_address").toString();
First parse the whole JSON into an Object. Then get an array called users, from that array, get index 0. From that Object, get data, and then email_address

The other option is to use jsonpath.
Using the same Json blob as Lorant:
{
"data": {
"email_address": "example#example.com"
}
}
You would use the following expression.
$.data.email_address
Or if it was an array, simply.
$.users.[data].email_address
An online tool can be used to experiment and learn the syntax, but if you know xpath it should be somewhat familiar already.

import org.json.JSONObject;
JSONObject json = new JSONObject(record);
json.getString("fieldName"));

Related

Null pointer observed while trying to fetch the object value from JSON array

I'm trying to loop the calls: JSON array and trying to fetch the machine details JSON object which is present under calls JSON array list as like below:
{
"<dynamicValue>":{
"type":"CORR-ID",
"tags":[
{
"name":"9VB6454145983212H",
"flags":[
"FLAG_DYNAMIC_VALUE",
"FLAG_ID_LOOKUP_SUPPORTED"
]
}
],
"callSummary":[
{
"colo":"lvs",
"pool":"amazon_paymentsplatformserv",
"machine":"stage2utb29958"
},
{
"colo":"lvs",
"pool":"amazon_elmoserv",
"machine":"msmamoserv_0"
},
{
"colo":"lvs",
"pool":"amazon_xopaymentgatewayserv",
"machine":"msmastmentgatewayserv_1"
},
{
"colo":"lvs",
"pool":"amazon_paymentapiplatserv",
"machine":"msmaentapiplatserv_2"
},
{
"colo":"lvs",
"pool":"amazon_userlifecycleserv_ca",
"machine":"stage2utb91581"
},
{
"colo":"lvs",
"pool":"amazon_dafproxyserv",
"machine":"msmasfproxyserv_1"
},
{
"colo":"lvs",
"pool":"paymentserv",
"machine":"te-alm-15757_paymentexecutionserv_0",
"calls":[
{
"colo":"lvs",
"pool":"fimanagementserv_ca",
"machine":"msmgementserv_ca_20"
},
{
"colo":"lvs",
"pool":"fimanagementserv_ca",
"machine":"msmasgementserv_ca_4"
}
]
}
]
}
}
The above JSON file which I stored in String variable and trying to fetch the machine details which is under calls: JSON ARRAY by using below code.
Code:
public static void getHttpUrlformachineList(String response, String CalId, String componentName)
throws Exception
{
//System.out.println(response);
Map<String, String> data = new HashMap<String, String>();
JSONParser parser = new JSONParser();
JSONObject object = (JSONObject) parser.parse(response);
JSONObject getValue = (JSONObject) object.get(CalId.trim()); //CalId is the dynamic value that mentioned in the JSON input file
JSONObject getCalSummary = (JSONObject) object.get("callSummary");
JSONArray arrays=(JSONArray) getCalSummary.get("calls");
System.out.println(arrays.size()); // return null pointer
}
Error:
java.lang.NullPointerException: null
at com.online.amazon.hadoop.cal.swagger.utils.Utils.getHttpUrlformachineList(Utils.java:112) ~[classes/:na]
If you notice that calls Array List will not be available in all the callSummary JSON Array, and It will be dynamic and can be available under any component that listed above.
So I just want to dynamically get the calls: JSON array and iterate and fetch machine details.
Can someone help me to achieve this?
Note: I'm using JSON-Simple library to parse and iterate the JSON. It would be great if I get solution on the same.
Updated:
I also tried to create callSummary as JSON array and loop that array to get each JSON object and tried to find the calls but this is also leads to Null pointer.
Also the calls json array is not index specific. It can be anywhere in the payload. It may or may not be there in the payload. I just need to handle if it's exist in any of the component then I need to fetch that machine details
change
JSONArray arrays=(JSONArray) getCalSummary.get("calls");
to
JSONArray arrays= getCalSummary.getJSONArray("calls")
and all other functions where you get objects instead of "get" you should use "getJSONObject", "getString" etc.. then you dont have to cast,
also im pretty sure its not arrays.size() its arrays.length() if you are using package org.json.JSONArray but since key "calls" doesnt exist in every "callSummary" you should check if its null or not before.
You should match the types as specified in your JSON string:
public static void getHttpUrlformachineList(String response, String CalId, String componentName)
throws Exception
{
//System.out.println(response);
Map<String, String> data = new HashMap<String, String>();
JSONParser parser = new JSONParser();
JSONObject object = (JSONObject) parser.parse(response);
JSONObject getValue = (JSONObject) object.get(CalId.trim()); //CalId is the dynamic value that mentioned in the JSON input file
JSONArray getCalSummary = (JSONArray) object.get("callSummary"); // callSummary is a JSONArray, not JSONObject
for (int i = 0; i < getCalSummary.length(); i++) {
JSONObject obj = getCalSummary.getJSONObject(i);
if (obj.has("calls")) {
// grab calls array:
JSONArray callsArray = obj.getJSONArray("calls");
}
}
}
Here, you should also check your JSON values with .has(...) method to avoid getting JSONException if a field doesn't exists in your JSONObject.

Convert JSON into List of Object property (Java)

I have simple json which looks like this :
[
{
"id":"0",
"name":"Bob",
"place":"Colorado",
},
{
"id":"1",
"name":"John",
"place":"Chicago",
},
{
"id":"2",
"name":"Marry",
"place":"Miami",
}
]
What I want is using Java to create list of strings (List<String>) that contains all 'names'. I have some experience using Gson and I think about something like:
Gson gson = new Gson();
String[] stringArray= gson.fromJson(jsonString, " ".class);
The problem with this method is that I should create some POJO class which I didn`t in this case. Is it any way I can achieve it without creating separate class with this 'name' property ?
Using Jackson to parse, and Java 8 Streams API for extracting only the name field; the following may help you:
// Your string
jsonString = "[{ \"id\":\"0\", \"name\":\"Bob\", \"place\":\"Colorado\" }, { \"id\":\"1\", \"name\":\"John\", \"place\":\"Chicago\"}, { \"id\":\"2\", \"name\":\"Marry\", \"place\":\"Miami\" }]";
// using Jackson to parse
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.getTypeFactory();
List<MyInfo> myObjectList = objectMapper.readValue(jsonString, typeFactory.constructCollectionType(List.class, MyInfo.class));
// Java 8 Collections
List<String> nameList = myObjectList.stream().map(MyInfo::getName).collect(Collectors.toList());
Beware, it implies the usage of a MyInfo class representing your a Java class in which Json objects of yours would fit in.
You can use JSONArray to get value from key 'name'. Like this:
JSONArray jSONArray = new JSONArray(yourJson);
List<String> list = new ArrayList<>();
for (int i = 0; i < jSONArray.length(); i++) {
JSONObject object = (JSONObject) jSONArray.get(i);
String value = object.getString("name");
System.out.println(value);
list.add(value);
}
You may try the following code snippet,
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
List<String> ls = new ArrayList<String>();
JSONObject jsonObj = new JSONObject();
JSONArray jsonArr = new JSONArray();
JSONParser jsonParse = new JSONParser();
String str = "[{\"id\": \"0\",\"name\": \"Bob\",\"place\": \"Colorado\"},"
+ "{\"id\": \"1\",\"name\": \"John\",\"place\": \"Chicago\"},"
+ "{\"id\": \"2\",\"name\": \"Marry\",\"place\": \"Miami\"}]";
try {
jsonArr= (JSONArray) jsonParse.parse(str); //parsing the JSONArray
if(jsonArr!=null){
int arrayLength =jsonArr.size(); //size is 3 here
for(int i=0;i<arrayLength;i++){
jsonObj = (JSONObject) jsonParse.parse(jsonArr.get(i).toString());
ls.add(jsonObj.get("name").toString()); //as we need only value of name into the list
}
System.out.println(ls);
}
} catch (ParseException e) {
e.printStackTrace();
}catch(Exception e1){
e1.printStackTrace();
}
As you have array, use JSONArray and used jsonParse to avoid any parsing error.
I have used json-simple API to acheive the above.

Hi, I need help parse through a JSON file in Java

I am trying to parse through a JSON file using the library JSON simple. The first two string are good. However, when I try to parse through object social I get facebook: null, Pinterest : null, and rss: null. How do I parse through my second object?
Here is my JSON file
{
"blogURL": "www.sheriyBegin",
"twitter": "http://twitter.com/Sherily",
"social": {
"facebook": "http://facebook.com/Sherily",
"pinterest": "https://www.pinterest.com/Sherily/Sherily-articles",
"rss": "http://feeds.feedburner.com/Sherily"
}
}
Here is the code I wrote
package javaugh;
import java.io.FileReader;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
public class JavaUgh {
public static void main(String[] args)throws Exception{
JSONParser parser = new JSONParser();
Object obj = parser.parse(new FileReader("C:\\Users\\HP\\Desktop\\Research\\file2.txt"));
JSONObject jsonObject = (JSONObject) obj;
String blog = (String)jsonObject.get("blogURL");
String twitter = (String)jsonObject.get("twitter");
JSONObject jsonObject2 = (JSONObject) obj;
String face = (String)jsonObject2.get("facebook");
String pin = (String)jsonObject2.get("pinterest");
String rss = (String)jsonObject2.get("rss");
System.out.println("Blog: "+ blog);
System.out.println("Twitter Page : " + twitter);
System.out.println("Socail:");
System.out.println("Facebook Page : " + face);
System.out.println("Pintersect: " + pin);
System.out.println("Rss : " + rss);
}
}
Output:
Blog: www.sheriyBegin
Twitter Page : http://twitter.com/Sherily
Socail:
Facebook Page : null
Pintersect: null
Rss : null
You should obtain the second json object from the first one, not by creating a new reference to the first one.
JSONObject jsonObject2 = (JSONObject) jsonObject.get("social");
JSONObject social = (JSONObject) jsonObject.get("social");
String face = (String)social.get("facebook");
String pin = (String)social.get("pinterest");
String rss = (String)social.get("rss");

Parsing multiple json objects in java

I have this json file that I'm trying to parse in my program.
{
"items": [{
"0": {
"item_name":"Test Item",
"item_rarity":2,
"item_material":"STICK",
"required_level":1,
"min_damage":100.0,
"max_damage":200.0,
"item_set":"The cool kids",
"attributes":[{"name":"lifesteal","modifier":20}]
},
"1": {
"item_name":"Test Item",
"item_rarity":2,
"item_material":"STICK",
"required_level":1,
"min_damage":100.0,
"max_damage":200.0,
"item_set":"The cool kids",
"attributes":[{"name":"lifesteal","modifier":20}]
}
}]
}
I am printing the JSON string, but instead of getting the individual objects (0, then 1, then 2, etc...) it only gets the whole array every time I print it out.
Object obj = jsonParser.parse(new FileReader(new File(ValaCraft.getInstance().getDataFolder() + "/test.json")));
JSONObject jsonObject = (JSONObject) obj;
JSONArray items = (JSONArray) jsonObject.get("items");
for (int i = 0; i < items.size(); i++) {
JSONObject item = (JSONObject) items.get(i);
System.out.print(item.toString());
}
Anybody have an idea on how to parse this file (without GSON, attributes is a custom class and I found it complicated to use the auto parse that gson comes with).
What did you find troubling with GSON?
If you pass it to the gson.fromJSON as a JSONObject class, it should work, and you'll be able to get data from the JSON object.
Gson gson = new Gson();
JsonObject jsonFile = gson.fromJson(file.json, JsonObject.class);
Then you can call
JsonArray array = jsonFile.get("items").getAsJsonArray();
Then to grab the attributes from the first element of the array.
array.get(0).getAsJsonObject().get("attributes").getAsJsonArray();

How to convert a snake_case JSON to nested JSON in java?

I have few cases where I want to convert a snake_case JSON to nested JSON
e.g.
{
"snake_case": {
"test": "value"
}
}
to
{
"snake": {
"case": {
"test": "value"
}
}
}
Is there any way to do this in java other then manually parsing the strings with _ or there any libraries are there in java?
Consider your JSON data as String:
String strjson="{snake_case: {test: value}}";
then
JSONObject jj=new JSONObject(strjson);
JSONObject jfinal=new JSONObject();
Iterator<String> itr=jj.keys();
while(itr.hasNext())
{
String key=itr.next();
if(key.contains("-"))
{
JSONObject jkey=jj.getJSONObject(key);
JSONObject jnew=new JSONObject();
jnew.put(key.split("-")[1],jkey);
jfinal.put(key.split("-")[0],jnew);
}
}
you can get the output in jfinal.
You could BSON to achieve this. Here is the code you would use.
//import java.util.ArrayList;
//import org.bson.Document;
//Declare three json object
Document root= new Document();
Document rootSnake = new Document();
Document rootSnakeCase = new Document();
//Add value to the most nested object
rootSnakeCase.append("test","value");
//combine the objects together
if (!rootSnakeCase.isEmpty()){
rootSnake.append("case",rootSnakeCase);
}
if (!rootSnake.isEmpty()){
root.append("snake",rootSnake);
}
//output code
System.out.println(root.toJson());

Categories

Resources