Read from .json file [duplicate] - java

This question already has answers here:
How to parse JSON in Java
(36 answers)
Closed 6 years ago.
Hii i am having trouble to read .json file in Java containing following structure,
{"id":"1", "name":"A", "address":{"plot no":"22", "street":"road"}}
{"id":"2", "name":"A", "address":{"plot no":"22", "street":"road"}}
{"id":"3", "name":"A", "address":{"plot no":"22", "street":"road"}}
{"id":"4", "name":"A", "address":{"plot no":"22", "street":"road"}}
I have such 10k records. I cant change structure. I want to read it and do processing on "address". I need an efficient way to read it and fetch only address. Any suggestions?

yourJsonObject is your json file extracted in java as a json object. And this:
JSONObject jso = yourJsonObject.getJSONObject("address") ;
will extract your "address" part as a json object. Then you can do all the classical processing on it.

You can use JSON simple library,i hope you take idea with this example ;
JSONParser parser = new JSONParser();
JSONArray a = (JSONArray) parser.parse(new FileReader("file name"));
for (Object o : a){
JSONObject person = (JSONObject) o;
String name = (String) person.get("name");
System.out.println(name);
String city = (String) person.get("city");
System.out.println(city);
String job = (String) person.get("job");
System.out.println(job);
JSONArray cars = (JSONArray) jsonObject.get("cars");
for (Object c : cars)
{
System.out.println(c+"");
}
}

Related

How to solve com.google.gson.JsonArray cannot be cast while parsing Json file in java [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I am parsing json file in java first time. Where my json file structure is fixed one (I can not change this). I have gone through different answers, but didn't help with my json.
I want list of all Group Name in one arrylist and Unit Name in another arraylist
Please help to resolve this error, Thanks
I used below code and tried to read from json, but failed to parsed.
JSON FILE:
[
{"No":"1","Component":"Amazon","group_id":"1","Group Name":"shop","Unit Name":"UN","PM":"NULL"},
{"No":"2","Component":"Amazon","group_id":"1","Group Name":"shop","Unit Name":"UM","PM":"NULL"},
{"No":"3","Component":"Amazon","group_id":"1","Group Name":"shop","Unit Name":"UP","PM":"NULL"},
{"No":"4","Component":"Amazon","group_id":"1","Group Name":"shop","Unit Name":"SO","PM":"NULL"},
{"No":"5","Component":"Amazon","group_id":"1","Group Name":"cart","Unit Name":"SP","PM":"NULL"},
{"No":"6","Component":"Amazon","group_id":"2","Group Name":"payment","Unit Name":"NZ","PM":"TRUE"}
]
Code Trial 1 :
JsonArray jsonArray = new JsonArray();
Object obj = new JsonParser().parse(new FileReader(JSON_FILE_PATH));
JsonObject jsonObject = jsonArray.getAsJsonObject();
String groupName = jsonObject.get("Group Name").toString();
ERROR: Exception in Test Case: (IllegalStateException: Not a JSON Object: [])
java.lang.IllegalStateException: Not a JSON Object: []
Code Trial 2:
Object obj = new JsonParser().parse(new FileReader(JSON_FILE_PATH));
JsonObject jsonObject = (JsonObject) obj;
String firstName = jsonObject.get("Group Name").toString();
ERROR: Exception in Test Case: (ClassCastException: com.google.gson.JsonArray cannot be cast to com.google.gson.JsonObject)
java.lang.ClassCastException: com.google.gson.JsonArray cannot be cast to com.google.gson.JsonObject
I have solved this issue with below code :
JsonArray jsonArray = new JsonParser().parse(new FileReader(fileName)).getAsJsonArray();
ArrayList<String> pmGrpListFromWebOm = new ArrayList<>();
for (JsonElement jsonObjectElement : jsonArray) {
JsonObject jsonObject = jsonObjectElement.getAsJsonObject();
String grpname= jsonObject.get("Group Name").toString();
pmGrpListFromWebOm.add(grpname);
}
The JSON file contains array of objects so you should be able to read the JsonArray immediately using parser.parse method and explicit casting.
Then you should iterate the array and access its JsonObject items using get method.
JsonParser parser = new JsonParser();
JsonArray jsonArray = (JsonArray) parser.parse(new FileReader(JSON_FILE_PATH));
for (int i = 0; i < jsonArray.size(); i++) {
JsonObject item = (JsonObject) jsonArray.get(i);
String groupName = item.get("Group Name").getAsString();
System.out.printf("%d group=%s%n", i, groupName); // item index and groupName
}
The output will be:
0 group=shop
1 group=shop
2 group=shop
3 group=shop
4 group=cart
5 group=payment
However, Gson JsonParser is deprecated and it is recommended to use Gson object mapper which allows to read/write objects in more type-safe way.
Each item in the example JSON can be considered as a map of key-value pairs, where both key and value are String.
Gson gson = new Gson();
// prepare type information
Type itemListType = new TypeToken<ArrayList<Map<String, String>>>(){}.getType();
// read the list
List<Map<String, String>> list = gson.fromJson(json, itemListType);
// process items in the list
for (Map<String, String> item : list) {
String no = item.get("No");
String groupName = item.get("Group Name");
System.out.printf("no=%s group=%s%n", no, groupName);
}
output:
no=1 group=shop
no=2 group=shop
no=3 group=shop
no=4 group=shop
no=5 group=cart
no=6 group=payment

How to get elements from a java string? [duplicate]

This question already has answers here:
How to parse JSON in Java
(36 answers)
Closed 2 years ago.
for example, I have this string
{"items":[{"match_id":"1-147440f1-7330-4c9c-9d3d-fab2e43e0754","version":2,"region":"EU"},{"match_id":"2-543985-ndakf-948129-dfsdafsda89fsda",
"version":2","region":"EU"}
how can I get only the "1-147440f1-7330-4c9c-9d3d-fab2e43e0754", so the next characters after match_id that are between " ". I need them as string so not int or anything else, just string.
Thank you!
This is using json-simple-1.1, you can download the jar or add the dependency via Maven/Gradle.
String json = "{\"items\":[{\"match_id\":\"1-147440f1-7330-4c9c-9d3d-fab2e43e0754\",\"version\":2,\"region\":\"EU\"},{\"match_id\":\"2-543985-ndakf-948129-dfsdafsda89fsda\", \"version\":\"2\",\"region\":\"EU\"}]}";
Object obj = new JSONParser().parse(json);
JSONObject jo = (JSONObject) obj;
JSONArray items = (JSONArray) jo.get("items");
List<String> matchIds = new ArrayList<>();
for(int i=0; i<items.size();i++) {
JSONObject item = (JSONObject) items.get(i);
matchIds.add(item.get("match_id").toString());
}
System.out.println(matchIds.get(0));

Iterate through a collection of JSON Objects

I have a JSON file called mani.json which contains several objects, each object containing 3 key-value pairs that have information about some artifact files.
{ "art_src_path": "source/subdir/hi-there.txt","art_id": "6945-L9.txt","art_date": "2018:03:10 01:10:33"}
{ "art_src_path": "source/hello-world.txt","art_id": "10426-L13.txt","art_date": "2018:03:10 01:10:33"}
{ "art_src_path": "source/subdir/testfile.txt","art_id": "50518-L66.txt","art_date": "2018:03:10 01:10:33"}
I want to iterate through each of these objects in another file called FileTest.java and get the value corresponding to art_src_path. My FileTest.java file contains code that looks like this:
<!-- language: java -->
JSONParser parser = new JSONParser();
JSONObject a = (JSONObject) parser.parse(new FileReader("mani.json"));
for (Object o : a ) {
String path = (String) o.get("art_src_path");
File myFile = new File(path);
System.out.println("Source path: "+path);
}
NetBeans prompts an error and states that the object returned by the parser is not iterable and so I cannot use the for-each loop.
While this code, with certain modifications, worked well for iterating through an array of objects, it seems to fail for iterating through an object of objects.
So I have 2 questions:
What does the parser return; so that it is iterable for an array but not for an object?
How can I iterate through all the objects in mani.json to get the value for art_src_path from each object?
Almost all the answer so far tell me how to iterate over an array of objects. I am able to do that. I need to know how to iterate over an object of objects.
Thank you.
Is mani.json file is correctly json format? If so, the list would be JSONArray. JSONArray can iterate but JSONObject cannot.
If mani.json file is not json format but just text file. read line by line and parse each as JSONObject.
String strJson = "[{ \"art_src_path\": \"source/subdir/hi-there.txt\",\"art_id\": \"6945-L9.txt\",\"art_date\": \"2018:03:10 01:10:33\"},"+
"{ \"art_src_path\": \"source/hello-world.txt\",\"art_id\": \"10426-L13.txt\",\"art_date\": \"2018:03:10 01:10:33\"},"+
"{ \"art_src_path\": \"source/subdir/testfile.txt\",\"art_id\": \"50518-L66.txt\",\"art_date\": \"2018:03:10 01:10:33\"}]" ;
System.out.println("input = "+strJson) ;
JSONParser parser = new JSONParser() ;
JSONArray a = (JSONArray) parser.parse(strJson) ;
for (Object o:a) {
String path = (String) ((JSONObject) o).get("art_src_path") ;
System.out.println("source path:"+path) ;
}

parse json using java (simplejson)

I need to parse json which I get from YQL but I am having trouble as I am not getting the results I need. I am using simple json (https://code.google.com/p/json-simple/wiki/DecodingExamples) and trying to follow the documentation. The problem is the example they show are very limited (I am very new to json). I want to extract everything in the array (Sy, Date, O, H, L, C, and V ). In the documentation they show how to extarct elements from an array if the json object is just as an array, but I have an array + some extra stuff on top:
{"query"
{"count":200,"created":"2014-06-17T00:46:43Z","lang":"en-GB","results"
This is the full json object, how would I extract just the array?
{"query"
{"count":200,"created":"2014-06-17T00:46:43Z","lang":"en-GB","results"
{"array":[{"Sy":"Y","Date":"2010-03-10","O":"16.51","H":"16.94","L":"16.51","C":"16.79","V":"33088600"},
{"Sy":"Y","Date":"2010-03-09","O":"16.41","H":"16.72","L":"16.40","C":"16.53","V":"20755200"},
{"Sy":"Y","Date":"2010-03-08","O":"16.32","H":"16.61","L":"16.30","C":"16.52","V":"30554000"}
]}}}
i use https://code.google.com/p/org-json-java/downloads/list
this is simple
try{
String json = "JSON source";
JSONObject j = new JSONObject(json);
JSONArray arr = j.getJSONObject("query").getJSONObject("results").getJSONArray("array");
for(int i=0; i<arr.length(); i++){
JSONObject obj = arr.getJSONObject(i);
String sy = obj.getString("Sy");
String date = obj.getString("Date");
String o = obj.getString("O");
String h = obj.getString("H");
String l = obj.getString("L");
String c = obj.getString("C");
String v = obj.getString("V");
}
}
catch(JSONException e){
}
You have to extract the array you need piece by piece.
JSONParser parser=new JSONParser();
String s="{YOUR_JSON_STRING}";
JSONArray array=parser.parse(s).get("query") //"query"
.get("result") // "query->result"
.get("array"); // THE array you need
Note that you might need to use try...catch... block to deal with exceptions.
Since you are using java, I highly recommend gson, which is written by google. It can convert json to object directly, which means you don't need to get the array deep inside the json step by step. https://code.google.com/p/google-gson/
Generally speaking, you can use gson to parse json piece by piece with jsonparser or, convert the whole json to a object with gson.

What Format is this List in? [duplicate]

This question already has answers here:
How to parse JSON in Java
(36 answers)
Closed 8 years ago.
I'm receiving data in the format:
"result": {"FirstData": {"One": 1, "Two": 2,...
First of all, what is this called usually in Java (2D array)?
Secondly, how do I loop over this to extract the strings?
I understand that if I only had "FirstData" in my array I can do:
public void onSuccess( String[] result)
{
for( String Name : result ) {
System.out.println(Name);
}
Going through the same logic for 2D arrays, it doesn't seem to print things out:
public void onSuccess( JSONObject result)
{ //Parse here
}
EDIT:
Yes it's JSON and it looks like the code has gson (google JSON) installed
EDIT 2:
ABOVE CODE NOW CORRECTED
JSON. Use a JSON parser to read the data. One popular parser for Java : google-gson
It looks kind of like JSON. JSON-strings is built like this:
Key: Values
However, Values can be new "key:values" so you can have:
"Key": ["InnerKey1":"Value1","Innerkey2","Value2"], "Key2": ["InnerKey1":"Value1","Innerkey2","Value2"] etc.
For you source:
JSONObject myJSONObject = new JSONObject("Your resultstring goes here");
JSONObject resultObject = myJSONObject.getJSONObject("result");
JSONObject FirstDataObject = resultObject.getJSONObject("FirstData"); //Object with JSONObjects "One","Two" etc
//Since the part " {"One": 1, "Two": 2,..." in your string isn't an JSONArray you cannot do the following but if it were like this "["One": 1, "Two": 2,..." your could do this:
JSONArray FirstDataArray = resultObject.getJSONObject("FirstData"); //Array with JSONObjects "One","Two" etc
JSONArray arr = resultObject.getJSONArray("FirstData");
for (int i = 0; i < arr.length(); i++)
{
String number = arr.getJSONObject(i).getString(0);
......
}
You can try using Google Gson, https://code.google.com/p/google-gson/. It can take JSON strings and convert them to Java objects.
Use a JSON parser for Java and you can probably convert it into objects. You can find a variety of Java-based JSON parsers on http://www.json.org/
This string is in the JSON format and hence it is recommended to use a JSON parser.
Read about JSON format in http://www.json.org/.
This link provides explains about JSON in java http://www.json.org/java/

Categories

Resources