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

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));

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

JSON parsing issue? [duplicate]

This question already has answers here:
How do I parse JSON in Android? [duplicate]
(3 answers)
Closed 4 years ago.
Im trying to parse a json for an android app.
Its in this format:
"ticker_24h":{
"total":{
"last":24171.580293457908,
"high":30808.7,
"low":21159.009,
"vol":864.2217252755704,
"vwap":23665.865289000638,
"money":20452554.930199366,
"trades":6463
},
"exchanges":{
"NEG":{
"last":24500,
"open":23125.08,
"high":24630,
"low":22850.04,
"vol":431.26271897999953,
"vwap":24037.00642046651,
"money":10366264.745030094,
"trades":1572
},
"MBT":{
"last":23893.87002,
"open":22880,
"high":24161.57992,
"low":22700,
"vol":102.92291203000005,
"vwap":23372.09484545152,
"money":2405524.0617352244,
"trades":1835
}
} }
So far I have this but im getting a json parse error on logcat.
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
JSONObject ticker = jsonObj.getJSONObject("ticker_24h");
JSONArray exchanges = ticker.getJSONArray("exchanges");
// looping through All exchanges
for (int i = 0; i < exchanges.length(); i++) {
JSONObject e = exchanges.getJSONObject(i);
String name = e.names().getString(i);
String price = e.getString("last");
// tmp hash map for single exchange
HashMap<String, String> exchange = new HashMap<>();
// adding each child node to HashMap key => value
exchange.put("name", name);
exchange.put("price", price);
// adding exchange to exchange list
exchangeList.add(exchange);
}
Ideally i would need a string called name with each key name and a string called price with each "last" value from these keys.
Try this code. I am using iterator to loop over the exchanges, the name of the exchange can be retrieved by iterator.next()
JSONObject exchanges = ticker.getJSONArray("exchanges");
for (Iterator i = exchanges.keys(); i.hasNext(); ) {
String keys = (String) i.next();
Util.logRanjith("Exchange name is " + keys);
JSONObject temp = (JSONObject) jsonObject.get(keys);
String last=temp.get("last").toString();
}

Put String value in gson.JsonArray [duplicate]

This question already has answers here:
How to add a String Array in a JSON object?
(5 answers)
Closed 6 years ago.
I want to store a String in a JsonArray.
Ex:
"virtual_hosts": [ "some_host"]
How should I do this, with the help of java.
JsonArray arr = new JsonArray();
arr.add()
This only lets me add a JsonObject, but I want to store a String.
If you are going to use gson by google, looks like you have to do it this way:
JsonPrimitive firstHost = new JsonPrimitive("vlbr-vlbre9ef7a820b3f43c7bd3418bb62.uscom-central-1.c9dev1.oc9qadev.com");
JsonArray jArray = new JsonArray();
jArray.add(firstHost);
JsonObject jObj = new JsonObject();
jObj.add("virtual_hosts", jArray);
The first line converts your java string into a json string.
In the next two steps, a json array is created and your string is added to it.
After that, a json object which is going to hold the array is created and the array is added with a key that makes the array accessible.
If you inspect the object, it looks exactly like you want to have it.
There is no simple way in adding just a string to an JsonArray if you want to use gson. If you need to add your string directly, you probably have to use another library.
You can create a list of hosts and set the property in JSON.
import org.json.simple.JSONObject;
import java.util.ArrayList;
public class Test {
public static void main(String[] args) {
ArrayList<String> hosts = new ArrayList<String>();
hosts.add("vlbr-vlbre9ef7a820b3f43c7bd3418bb62.uscom-central-1.c9dev1.oc9qadev.com");
hosts.add("dummy.oc9qadev.com");
JSONObject jsonObj = new JSONObject();
jsonObj.put("virtual_hosts", hosts);
System.out.println("Final JSON String is--"+jsonObj.toString());
}
}
Output -
{ "virtual_hosts":
["vlbr-vlbre9ef7a820b3f43c7bd3418bb62.uscom-central-1.c9dev1.oc9qadev.com",
"dummy.oc9qadev.com"] }
What you are trying to do is storing a JSONArray into a JSONObject. Because the key virtual_hosts is going to contain a value as JSONArray.
Below code can help you.
public static void main( String[] args ) {
JSONArray jsonArray = new JSONArray();
jsonArray.add( "vlbr-vlbre9ef7a820b3f43c7bd3418bb62.uscom-central-1.c9dev1.oc9qadev.com" );
JSONObject jsonObject = new JSONObject();
jsonObject.put( "virtual_hosts", jsonArray );
System.out.println( jsonObject );
}
Output:
{"virtual_hosts":["vlbr-vlbre9ef7a820b3f43c7bd3418bb62.uscom-central-1.c9dev1.oc9qadev.com"]}
Maven dependecny
<dependency>
<groupId>net.sf.json-lib</groupId>
<artifactId>json-lib</artifactId>
<version>2.4</version>
<classifier>jdk15</classifier>
</dependency>

Read from .json file [duplicate]

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+"");
}
}

How to store JSON response in an array list? [duplicate]

This question already has answers here:
Converting JSONarray to ArrayList
(23 answers)
Closed 8 years ago.
I want to store a JSON response in array list so that it will be easy to fetch data and assign it to other variables.
This is my JSON response:
{
"statusCode":"1001",
"message":"Success",
"response":{
"holidays":[
{
"holidayId":78,
"year":2015,
"date":"2015-01-01",
"day":"Thrusday",
"occasion":"New Year Day",
},
{
"holidayId":79,
"year":2015,
"date":"2015-01-15",
"day":"Thrusday",
"occasion":"Pongal/Sankranthi",
},
{
"holidayId":80,
"year":2015,
"date":"2015-01-26",
"day":"Monday",
"occasion":"Republic Day",
}
],
"year":0
}
}
This is the way I am fetching data from the response:
JSONObject jobj = new JSONObject(result);
String statusCode = jobj.getString("statusCode");
if (statusCode.equalsIgnoreCase("1001"))
{
System.out.println("SUCCESS!");
String response = jobj.getString("response");
JSONObject obj = new JSONObject(response);
String holidays = obj.getString("holidays");
ArrayList<HolidayResponse> holidayResponse = holidays; //This stmt. shows me error
}
How do I solve this issue? Please help me.
that is because of a JSON parse exception:
the holidays is a JSON array.Hence the correct way would be:
JSONObject obj = new JSONObject(response);
JSONArray holidays = obj.getJSONArray("holidays");
look here to convert that to array list.
Instead of all this hassle,you could use Gson or Jackson

Categories

Resources