How to traverse through each node of jsonString - java

Can you please explain me where i am going wrong, am able to traverse each node but getting exceptions..
Have written code recursively to traverse through the jsonstring,
public static void main(String [] args) {
String jsonString = "{ \"developers\": [{ \"firstName\":\"Linus\" , \"lastName\":\"Torvalds\" }, " +
"{ \"firstName\":\"John\" , \"lastName\":\"von Neumann\" } ]}";
parse(jsonString);
}
public static void parse(Object jsonString) {
try {
JSONObject jsonObject = new JSONObject(jsonString.toString());
Iterator<String> iter = jsonObject.keys();
while (iter.hasNext()) {
String key = iter.next();
Object value = jsonObject.get(key);
System.out.println(key+"==>"+value);
parse(value);
}
} catch (JSONException e) {
try {
JSONArray jsonArray = new JSONArray(jsonString.toString());
for (int i = 0; i < jsonArray.length(); i++)
{
Object value = jsonArray.get(i);
System.out.println("**"+value);
parse(value);
}
} catch (JSONException e1) {
e1.printStackTrace();
}
e.printStackTrace();
}

JSON string is a key value pairs and many libraries gives access to traverse through...
Here is one of the example.
import org.json.simple.JSONObject;
import org.json.simple.JSONArray;
import org.json.simple.parser.ParseException;
import org.json.simple.parser.JSONParser;
class JsonDecodeDemo
{
public static void main(String[] args)
{
JSONParser parser=new JSONParser();
String s = "[0,{\"1\":{\"2\":{\"3\":{\"4\":[5,{\"6\":7}]}}}}]";
try{
Object obj = parser.parse(s);
JSONArray array = (JSONArray)obj;
System.out.println("The 2nd element of array");
System.out.println(array.get(1));
System.out.println();
JSONObject obj2 = (JSONObject)array.get(1);
System.out.println("Field \"1\"");
System.out.println(obj2.get("1"));
s = "{}";
obj = parser.parse(s);
System.out.println(obj);
s= "[5,]";
obj = parser.parse(s);
System.out.println(obj);
s= "[5,,2]";
obj = parser.parse(s);
System.out.println(obj);
}catch(ParseException pe){
System.out.println("position: " + pe.getPosition());
System.out.println(pe);
}
}
}
Find it really interesting here.
The same example, I have formatted the JSON string which you published,
public static void main(String[] args) {
String jsonString = "{\"developers\":[{\"firstName\":\"Linus\",\"lastName\":\"Torvalds\"},{\"firstName\":\"John\",\"lastName\":\"von Neumann\"}]}";
parse(jsonString);
}
public static void parse(Object jsonString) {
try {
JSONObject jsonObject = new JSONObject(jsonString.toString());
Iterator<String> iter = jsonObject.keys();
while (iter.hasNext()) {
String key = iter.next();
Object value = jsonObject.get(key);
System.out.println(key + "==>" + value);
parse(value);
}
}
catch (JSONException e) {
try {
JSONArray jsonArray = new JSONArray(jsonString.toString());
for (int i = 0; i < jsonArray.length(); i++)
{
Object value = jsonArray.get(i);
System.out.println("**" + value);
parse(value);
}
}
catch (JSONException e1) {
// e1.printStackTrace();
}
// e.printStackTrace();
}
}
Output:
developers==>[{"lastName":"Torvalds","firstName":"Linus"},{"lastName":"von Neumann","firstName":"John"}]
**{"lastName":"Torvalds","firstName":"Linus"}
lastName==>Torvalds
firstName==>Linus
**{"lastName":"von Neumann","firstName":"John"}
lastName==>von Neumann
firstName==>John

Related

JSON flattener returning only last object from JSON to a flattened form

I have a JSON that looks like below,
{
"users": [
{
"displayName": "Sharad Dutta",
"givenName": "",
"surname": "",
"extension_user_type": "user",
"identities": [
{
"signInType": "emailAddress",
"issuerAssignedId": "kkr007#gmail.com"
}
],
"extension_timezone": "VET",
"extension_locale": "en-GB",
"extension_tenant": "EG12345"
},
{
"displayName": "Sharad Dutta",
"givenName": "",
"surname": "",
"extension_user_type": "user",
"identities": [
{
"signInType": "emailAddress",
"issuerAssignedId": "kkr007#gmail.com"
}
],
"extension_timezone": "VET",
"extension_locale": "en-GB",
"extension_tenant": "EG12345"
}
]
}
I have the above code and it is able to flatten the JSON like this,
{
"extension_timezone": "VET",
"extension_tenant": "EG12345",
"extension_locale": "en-GB",
"signInType": "userName",
"displayName": "Wayne Rooney",
"surname": "Rooney",
"givenName": "Wayne",
"issuerAssignedId": "pdhongade007",
"extension_user_type": "user"
}
But the code is returning only the last user in the "users" array of JSON. It is not returning the first user (essentially the last user only, no matter how many users are there) just the last one is coming out in flattened form from the "users" array.
public class TestConvertor {
static String userJsonAsString;
public static void main(String[] args) throws JSONException {
String userJsonFile = "C:\\Users\\Administrator\\Desktop\\jsonRes\\json_format_user_data_input_file.json";
try {
userJsonAsString = readFileAsAString(userJsonFile);
} catch (Exception e1) {
e1.printStackTrace();
}
JSONObject object = new JSONObject(userJsonAsString); // this is your input
Map<String, Object> flatKeyValue = new HashMap<String, Object>();
System.out.println("flatKeyValue : " + flatKeyValue);
readValues(object, flatKeyValue);
System.out.println(new JSONObject(flatKeyValue)); // this is flat
}
static void readValues(JSONObject object, Map<String, Object> json) throws JSONException {
for (Iterator it = object.keys(); it.hasNext(); ) {
String key = (String) it.next();
Object next = object.get(key);
readValue(json, key, next);
}
}
static void readValue(Map<String, Object> json, String key, Object next) throws JSONException {
if (next instanceof JSONArray) {
JSONArray array = (JSONArray) next;
for (int i = 0; i < array.length(); ++i) {
readValue(json, key, array.opt(i));
}
} else if (next instanceof JSONObject) {
readValues((JSONObject) next, json);
} else {
json.put(key, next);
}
}
private static String readFileAsAString(String inputJsonFile) throws Exception {
return new String(Files.readAllBytes(Paths.get(inputJsonFile)));
}
}
Please suggest where I am doing wrong or my code needs modification.
Please try the below approach, this will give you a comma separated format for both user and identifier (flat file per se),
public static void main(String[] args) throws JSONException, ParseException {
String userJsonFile = "path to your JSON";
final StringBuilder sBuild = new StringBuilder();
final StringBuilder sBuild2 = new StringBuilder();
try {
String userJsonAsString = convert your JSON to string and store in var;
} catch (Exception e1) {
e1.printStackTrace();
}
JSONParser jsonParser = new JSONParser();
JSONObject output = (JSONObject) jsonParser.parse(userJsonAsString);
try {
JSONArray docs = (JSONArray) output.get("users");
Iterator<Object> iterator = docs.iterator();
while (iterator.hasNext()) {
JSONObject userEleObj = (JSONObject)iterator.next();
JSONArray nestedIdArray = (JSONArray) userEleObj.get("identities");
Iterator<Object> nestIter = nestedIdArray.iterator();
while (nestIter.hasNext()) {
JSONObject identityEleObj = (JSONObject)nestIter.next();
identityEleObj.keySet().stream().forEach(key -> sBuild2.append(identityEleObj.get(key) + ","));
userEleObj.keySet().stream().forEach(key -> {
if (StringUtils.equals((CharSequence) key, "identities")) {
sBuild.append(sBuild2.toString());
sBuild2.replace(0, sBuild2.length(), "");
} else {
sBuild.append(userEleObj.get(key) + ",");
}
});
}
sBuild.replace(sBuild.lastIndexOf(","), sBuild.length(), "\n");
}
System.out.println(sBuild);
} catch (Exception e) {
e.printStackTrace();
}
}

How to parse a json file into a json object in java

I am trying to parse a json file in java. However I keep receiving an error.
This is the file I am trying to parse:
[{
"name": "John Smith",
"totalSales": 250,
"salesPeriod": 10,
"experienceMultiplier": 0.5
},
{
"name": "David Prowless",
"totalSales": 250,
"salesPeriod": 10,
"experienceMultiplier": 0.5
}
]
This is what I have tried:
public static void main(String[] args)
{
JSONParser parser = new JSONParser();
try {
Object obj = parser.parse(new FileReader("data.json"));
JSONObject jsonObject = (JSONObject) obj;
String name = (String) jsonObject.get("name");
System.out.println(name);
String totalSales = (String) jsonObject.get("totalSales");
System.out.println(totalSales);
String salesPeriod = (String) jsonObject.get("salesPeriod");
System.out.println(salesPeriod);
String exp = (String) jsonObject.get("exp");
System.out.println(exp);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
}
This is the error I receive:
Exception in thread "main" java.lang.ClassCastException: org.json.simple.JSONArray cannot be cast to org.json.simple.JSONObject
at mentormate.json.MentormateJson.main(MentormateJson.java:23)
Java Result: 1
I apologize if this is a silly question with a simple solution. I am new to json.
EDIT:
I have decided to go along with the code below. However, I cannot set the for each loop right to iterate through object in the json file.
public static void main(String[] args) {
JSONParser parser = new JSONParser();
try {
Object obj = parser.parse(new FileReader("data.json"));
JSONArray jsonObjects = (JSONArray) obj;
for ( JSONObject jsonObject : jsonObjects) {
String name = (String) jsonObject.get("name");
System.out.println(name);
String totalSales = (String) jsonObject.get("totalSales");
System.out.println(totalSales);
String salesPeriod = (String) jsonObject.get("salesPeriod");
System.out.println(salesPeriod);
String exp = (String) jsonObject.get("exp");
System.out.println(exp);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
}
FINAL EDIT (PROBLEM SOLVED):
public static void main(String[] args) {
JSONParser parser = new JSONParser();
try {
Object obj = parser.parse(new FileReader("data.json"));
JSONArray jsonObjects = (JSONArray) obj;
for (Object o : jsonObjects) {
JSONObject jsonObject = (JSONObject) o;
String name = (String) jsonObject.get("name");
System.out.println(name);
Long totalSales = (Long) jsonObject.get("totalSales");
System.out.println(totalSales);
Long salesPeriod = (Long) jsonObject.get("salesPeriod");
System.out.println(salesPeriod);
Double exp = (Double) jsonObject.get("experienceMultiplier");
System.out.println(exp);
System.out.println();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
}
Please try this:
public static void main(String[] args) {
JSONParser parser = new JSONParser();
try {
Object obj = parser.parse(new FileReader("data.json"));
JSONArray jsonObjects = (JSONArray) obj;
for (Object o : jsonObjects) {
JSONObject jsonObject = (JSONObject) o;
String name = (String) jsonObject.get("name");
System.out.println(name);
Long totalSales = (Long)jsonObject.get("totalSales");
System.out.println(totalSales);
String salesPeriod = (String) jsonObject.get("salesPeriod");
System.out.println(salesPeriod);
String exp = (String) jsonObject.get("exp");
System.out.println(exp);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
}
Your data contains a JSON array, not a JSON object.
Change the line
JSONObject jsonObject = (JSONObject) obj;
to
JSONArray jsonArray = (JSONArray) obj;
This array will contain two JSONObjects.
you can use alibaba's fastjson.You can download fastjson jar file,this is pom xml:
<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.56</version>
</dependency>
when you import this jar,you can code like this:
import com.alibaba.fastjson.JSONObject;
import java.util.List;
public class MainTest {
public static void main(String[] args) {
String json = "[\n" +
"{\n" +
"\"name\": \"John Smith\",\n" +
"\"totalSales\": 250,\n" +
"\"salesPeriod\": 10,\n" +
"\"experienceMultiplier\": 0.5\n" +
"},\n" +
"{\n" +
"\"name\": \"David Prowless\",\n" +
"\"totalSales\": 250,\n" +
"\"salesPeriod\": 10,\n" +
"\"experienceMultiplier\": 0.5\n" +
"}\n" +
"]";
List<JSONObject> jsonObjects = JSONObject.parseArray(json,JSONObject.class);
jsonObjects.stream().forEach(System.out::print);
}
}
Please find whole example below.
1) Create DTO class with your params like,
class JsonParam {
private String name;
private int totalSales;
private int salesPeriod;
private float experienceMultiplier;
//Getter and setters
}
2) Then add Gson jar with min. version (2.2.4) - get online, or add dependency for maven structure.
3) Finally, add 2 lines in your code to get any parameter like,
List<JsonParam> jsonParams = new Gson().fromJson(json, new TypeToken<List<JsonParam>>() {}.getType());
System.out.println(jsonParams.get(0).getName());
In above statement, I have used 0 index, you can use for-loop as per your requirement.
try {
JSONParser parser = new JSONParser();
try {
Object obj = parser.parse(new FileReader("./test.json"));
// parsing the JSON string inside the file that we created earlier.
JSONArray jsonarray = (JSONArray) obj;
for (int i = 0; i < jsonarray.size(); i++) {
JSONObject jsonObject = (JSONObject) jsonarray.get(i);
String name = (String) jsonObject.get("name");
System.out.println(name);
long totalSales = (long) jsonObject.get("totalSales");
System.out.println(totalSales);
long salesPeriod = (long) jsonObject.get("salesPeriod");
System.out.println(salesPeriod);
Double exp = (Double) jsonObject.get("experienceMultiplier");
System.out.println(exp);
}
} catch (Exception e) {
e.printStackTrace();
}
Try this one

Extract JSON Keynames in Java

I want to extract JSON structure (only keyNames structure) by preserving the hierarchy (parent child relationship); I don't want values from the JSON yet.
I am new to Java and have been tying to achieve this using Jackson , but with no success.
Any direction on this will be much appreciated.
I created a static inner class for you by using JSONObject (http://www.json.org/javadoc/org/json/JSONObject.html)
public static class KeyNode {
private String name;
private ArrayList<KeyNode> children;
public KeyNode(String name) {
this.name = name;
this.children = new ArrayList<KeyNode>();
}
public void addChild(KeyNode child) {
this.children.add(child);
}
public static void parseJsonToKeys(KeyNode node, JSONObject json) throws JSONException {
Iterator<?> keys = json.keys();
while (keys.hasNext()) {
String name = (String) keys.next();
KeyNode child = new KeyNode(name);
node.addChild(child);
if (json.optJSONObject(name) != null) {
parseJsonToKeys(child, json.getJSONObject(name));
} else if (json.optJSONArray(name) != null) {
JSONArray array = json.getJSONArray(name);
for (int i = 0; i < array.length(); i++) {
try {
array.getJSONObject(i);
parseJsonToKeys(child, json.getJSONObject(name));
} catch (JSONException e) {
// this is ok
}
}
}
}
}
public static void exampleCodeUsage() {
try {
JSONObject json = new JSONObject("your json");
KeyNode keyHierarchy = new KeyNode("root");
parseJsonToKeys(keyHierarchy, json);
} catch (JSONException e) {
// your json is not formatted correctly
}
}
}
JSONParser parser = parser;
Object obj = parser.parse(new FileReader(FileName.Json));
JSONObject jobj = (JSONObject) obj;
obj.keys()
The method will give you the list of all keys in JSONObject

I can't loop through JSON Array for next Array

I try to learn Loop through a JSON object in Java for loop this case.But My json loop first array(ident AFL274) and stop not loop next array(CQH8971)(in json data have 2 arrays)I call this function by button.
this for call for json
public String getInfo(String url) {
try {
String result = HttpGet(url);
JSONObject json = new JSONObject(result);
JSONObject val = json.getJSONObject("SearchResult");
JSONArray data = val.getJSONArray("aircraft");
for(int i=0;i<data.length();i++)
{
JSONObject data1 = data.getJSONObject(i);
String ans = data1.getString("ident");
}
} catch (JSONException e) {
e.printStackTrace();
}
return ans;
}
and this JSON:
{
"SearchResult": {
"next_offset": -1,
"aircraft": [
{
"ident": "AFL274",
"type": "B77W"
},
{
"ident": "CQH8971",
"type": "A320"
}
]
}
}
Try this,
public String[] getInfo(String url) {
try {
String result = HttpGet(url);
JSONObject json = new JSONObject(result);
JSONObject val = json.getJSONObject("SearchResult");
JSONArray data = val.getJSONArray("aircraft");
int arrayLength = data.length();
String[] strAryAns = new String[arrayLength];
for(int i=0;i<arrayLength;i++)
{
JSONObject data1 = data.getJSONObject(i);
strAryAns[i] = data1.getString("ident");
}
} catch (JSONException e) {
e.printStackTrace();
}
return strAryAns;
}

How to modify values of JsonObject / JsonArray directly?

Once i have parsed a JSON String into a GSON provided JsonObject class, (assume that i do not wish to parse it into any meaningful data objects, but strictly want to use JsonObject), how am i able to modify a field / value of a key directly?
I don't see an API that may help me.
https://static.javadoc.io/com.google.code.gson/gson/2.6.2/com/google/gson/JsonObject.html
Strangely, the answer is to keep adding back the property. I was half expecting a setter method. :S
System.out.println("Before: " + obj.get("DebugLogId")); // original "02352"
obj.addProperty("DebugLogId", "YYY");
System.out.println("After: " + obj.get("DebugLogId")); // now "YYY"
This works for modifying childkey value using JSONObject.
import used is
import org.json.JSONObject;
ex json:(convert json file to string while giving as input)
{
"parentkey1": "name",
"parentkey2": {
"childkey": "test"
},
}
Code
JSONObject jObject = new JSONObject(String jsoninputfileasstring);
jObject.getJSONObject("parentkey2").put("childkey","data1");
System.out.println(jObject);
output:
{
"parentkey1": "name",
"parentkey2": {
"childkey": "data1"
},
}
Since 2.3 version of Gson library the JsonArray class have a 'set' method.
Here's an simple example:
JsonArray array = new JsonArray();
array.add(new JsonPrimitive("Red"));
array.add(new JsonPrimitive("Green"));
array.add(new JsonPrimitive("Blue"));
array.remove(2);
array.set(0, new JsonPrimitive("Yelow"));
Another approach would be to deserialize into a java.util.Map, and then just modify the Java Map as wanted. This separates the Java-side data handling from the data transport mechanism (JSON), which is how I prefer to organize my code: using JSON for data transport, not as a replacement data structure.
It's actually all in the documentation.
JSONObject and JSONArray can both be used to replace the standard data structure.
To implement a setter simply call a remove(String name) before a put(String name, Object value).
Here's an simple example:
public class BasicDB {
private JSONObject jData = new JSONObject;
public BasicDB(String username, String tagline) {
try {
jData.put("username", username);
jData.put("tagline" , tagline);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public String getUsername () {
String ret = null;
try {
ret = jData.getString("username");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return ret;
}
public void setUsername (String username) {
try {
jData.remove("username");
jData.put("username" , username);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public String getTagline () {
String ret = null;
try {
ret = jData.getString("tagline");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return ret;
}
public static JSONObject convertFileToJSON(String fileName, String username, List<String> list)
throws FileNotFoundException, IOException, org.json.simple.parser.ParseException {
JSONObject json = new JSONObject();
String jsonStr = new String(Files.readAllBytes(Paths.get(fileName)));
json = new JSONObject(jsonStr);
System.out.println(json);
JSONArray jsonArray = json.getJSONArray("users");
JSONArray finalJsonArray = new JSONArray();
/**
* Get User form setNewUser method
*/
//finalJsonArray.put(setNewUserPreference());
boolean has = true;
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
finalJsonArray.put(jsonObject);
String username2 = jsonObject.getString("userName");
if (username2.equals(username)) {
has = true;
}
System.out.println("user name are :" + username2);
JSONObject jsonObject2 = jsonObject.getJSONObject("languages");
String eng = jsonObject2.getString("Eng");
String fin = jsonObject2.getString("Fin");
String ger = jsonObject2.getString("Ger");
jsonObject2.put("Eng", "ChangeEnglishValueCheckForLongValue");
System.out.println(" Eng : " + eng + " Fin " + fin + " ger : " + ger);
}
System.out.println("Final JSON Array \n" + json);
jsonArray.put(setNewUserPreference());
return json;
}

Categories