JSON parsing issue? [duplicate] - java

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

Related

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

count key value in JSON and extract values

I have following JSONObject (not array, which I don't mind to convert). I am trying to do two things:
get the count of genre entry as "poetry" (count = 2).
get the key value of author name and genre:
authorName = malcolm
genreName = newsarticle
authorName = keats
genreName = poetry
{ "AddressBook" :{
"Details" :{
"authorname" :{
"Author-malcolm":{
"genre" :"poetry"
}
"Author-keats":{
"genre" :"poetry"
}
}
}
}
}
Code which I tried:
public static void main(String[] args) throws Exception, IOException, ParseException {
JSONParser parser = new JSONParser();
Object obj = parser.parse(new FileReader("My path to JSON"));
JSONObject jsonObject = (JSONObject) obj;
JSONArray arrayhere = new JSONArray();
arrayhere.add(obj);
System.out.println(arrayhere);
int count = 0;
for(int i = 0; i < arrayhere.size(); i++) {
JSONObject element = arrayhere.getJSONObject(i);//The method getJSONObject(int) is undefined for the type JSONArray
String branchName = element.getString("genre");//The method getString(String) is undefined for the type JSONObject
if(branchName.equals("poetry")) {
count ++;
}
}
System.out.println("Count f0r poetry genre=" + count);
}
}
I have looked at solutions all over. There is no question similar to this at stackoverflow. I am not sure if the procedure is correct.
A few problems here.
First, I'm not sure where you got that example JSON but you can't work with that. That's not even valid JSON Formatting.
Looks like you want something like this:
{
AddressBook:
[
{
authorname: "author-malcom",
genre:"poetry"
},
{
authorname: "author-keats",
genre: "poetry"
}
]
}
That's the structure you're trying to create in JSON.
So, you're parsing this in from a file into a JSONObject that has a key called AddressBook inside of it. That key points to an array of JSONObjects representing authors. Each of those objects will have a key called genre. You're trying to access the genre key and count on a condition.
What you did above was create attempt to create a JSONObject from an invalid string, and then add the entire JSONObject itself into the JSONArray. JSONArray.add() doesn't convert an object to an array, it literally adds it onto the array.
jsonObj => {"Name":"name1","Id":1000}
jsonArray.add(jsonObj)
jsonArray => [{"Name":"name1","Id":1000}]
That's what you did in your code above. You didn't create an array from a JSONObject, you added an object to the array.
Proper use is going to look like:
Object obj = parser.parse(new FileReader("path_to_file"));
JSONObject jobj = (JSONObject) obj;
//access key AddressBook
JSONArray author_array = jobj.getJSONArray("AddressBook");
int poetry = 0;
for(int i = 0; i < author_array.length(); i++) {
JSONObject author = (JSONObject) author_array.get(i);
if(author.getString("genre").equals("poetry")) {
poetry++;
}
}
To summarize, you're problems come from a lack of understanding about JSON Formatting and how to access elements within a JSON Object.
Paste in the sample JSONObject I gave you above here. That site will let you visualize what you're working with.

How to put an value to the extracting JSON and display it

I wanna display a parsed json with my values . I mean , I wanna add some values to the json and display it . I can display all result from respond , but I wanna display just the json with my values not all data :)
here i have parsed allready my json
JSONObject jsonObject = new JSONObject(adresUrl);
JSONArray offerResources = jsonObject.getJSONArray("offerResources");
for(int y = 0; y < offerResources.length(); y++){
JSONObject currentTransfer = offerResources.getJSONObject(y);
JSONArray meetPoint = currentTransfer.getJSONArray("meetPoints");
for (int i = 0; i < meetPoint.length(); i++){
JSONObject currentMeetPoints = meetPoint.getJSONObject(i);
String startAddress = currentMeetPoints.getString("startAddress"); // here i wanna put some values , but i dont know how
// here is a litle piece of my json :)
"meetPoints": [
{
"startAddress": "....", // after the collon i have to put my value .
"startLocation": {
thank you for your help
I'm not sure if I understood your question fully but from what I got here is some solution. I simply created a string and couple of Json objects and jsonarray for adding the list of values and put it inside the main json object "jsonValueObject " and accumulate it inside meetPoints.
Accumulate(String key,Object Value) is a key value pair, meaning if key is created then Object is checked for being an array,and if this array has "values", it will be added else new array will be created. "Put" will replace the value if the key exists.
String jsonString = "{\"results\":[{\"Country\":\"value\",\"state\":\"value\" },
{ \"Country\":\"value\", \"state\":\"value\"}]}";
JSONObject meetPoints = new JSONObject(jsonDataString);
JSONObject jsonValueObject = new JSONObject();
JSONArray list = new JSONArray();
jsonValueObject.put("Country", "newValue");
jsonValueObject.put("state", "newValue");
jsonValueObject.put("city", "Chennai");
jsonValueObject.put("street", "Bharathiyar Street");
jsonValueObject.put("date", "14May2017");
jsonValueObject.put("time", "10:00AM");
list.put(jsonValueObject);
meetPoints.accumulate("values", list);
System.out.println(meetPoints);

Fetch the key value from JSON String Android [duplicate]

This question already has answers here:
How to parse JSON in Java
(36 answers)
Closed 6 years ago.
I want to display all data in Key value pair in a below JSON String.
response {
community: “worker”
communitystr: "<null>";
workspace: abs;
email: "<null>";
admin: false;
persona: "<null>";
userinfo: {
info: {
contact1: {
firstname: “jon”;
lastname: “Doe”
phone: “9885678905”;
objectname: contact;
id: 9;
};
event1: {
eventname: “party”;
description: "";
order: 6;
id: 4;
objectname: events;
};
files: {
filename: “sample”;
description: "";
order: 11;
id: 11;
objectname: files;
};
};
};
As I am new to this finding difficulty. how to get the key value in array or any other accessible format ? thanks for any help
First your json format is not correct, if you try to use JSONObject or GSON library is will throw not json type exception.
Please use a correct format of json something like this.
{
[
{
username: "somename",
userId : "1"
},
{
username: "somename2",
userId: "2"
}
]
}
General JSONObject contain JSONArray or JSONObject which you can parse it using android built in JSON.
JSONArray jsonArray = new JSONArray(yourJSONArray);
for(int i = 0; i < jsonArray.length(); i++){
JSONObject json = jsonArray.getJSONObject(i);
String username = json.getString("username"); //here is how to get username key
}
Here is how you loop through every key and value inside your JSON object
JSONArray array = new JSONObject(result);
Iterator<String> iter = jsonObject.keys();
while (iter.hasNext()) {
String key = iter.next();
String value = jsonObject.getString(key)
Log.d(TAG,"key = "+key+" value = "+value); // always use tag in log cat for preventing confusion
}
Regardless anything you still need to have a proper format of JSON.

How to parse JSON block in java

I have some piece of JSON information.
Example:
"Items":[{"User":{"Id":"123","name":"abcdef","email":"xy#z.com"},"User":{"Id":"456","name":"def","email":"we#z.com"}}]
I want to remove symbols such as '{','"' and '}' and store it in the ArrayList such that each element in the JSON has a separate position in a new ArrayList.
The output i am expecting looks somewhat like this:
ArrayList[0][0]:Id
ArrayList[0][1]:123
ArrayList[1][0]:name
ArrayList[1][1]:abcdef
etc.,
Sample code:
public String[] ParseGetJSON (String str){
String text = str;
try{
JSONParser jsonParser = new JSONParser();
JSONObject jsonObj = (JSONObject) jsonParser.parse(text);
JSONArray item = (JSONArray) jsonObj.get("Items");
for(int i = 0;i<item.size();i++){
System.out.println("The "+i+" element of the array"+item.get(i));
}
The Output:
The 0 element of the array: {"Id":"123","name":"abcdef","email":"xy#z.com"}
The problem you are having is that your original input JSON is nested more deeply than you are parsing. The output you are seeing when you call item.get(i) makes it clear that each element of item is also a JSONObject, each of which has three fields (Id, name, email).
What you want to do is treat each element as the JSONObject it is, and parse it as well:
for(int i = 0;i<item.size();i++) {
// get the next element as a Object and print it
System.out.println("The "+i+" element of the array: "+item.get(i));
// get the next element as a JSONObject
JSONObject obj = item.getJSONObject(i);
Iterator<String> itr = obj.keys();
// print all its keys/value pairs
while (itr.hasNext()) {
String key = itr.next();
String value = obj.getString(key);
System.out.println("key=" + key + ", value=" + value);
// key=email, value=xy#z.com
// key=name, value=abcdef
// key=Id, value=123
// ...
}
}
Once you have extracted each key and value, you can do whatever you want with them.

Categories

Resources