Parse a JSON-string in Android - java

Right now I have the following JSON string:
"{"1":{"from":"540","to":"1020"},"2":{"from":"540","to":"1020"},"3":{"from":"540","to":"1020"},"4":{"from":"540","to":"1020"},"5":{"from":"540","to":"1020"},"6":{"from":"540","to":"1020"},"7":{"from":"540","to":"1020"}}"
and I want to parse it in Android Studio and iterate all just for this kind of result:
String day = monday;
int hourstart = from;
int hoursclose = to;
of course from and to means numbers. Does anyone know how construction of a JSON parser should look like?

Try this:
//here jsonString is your json in string format
JSONObject obj3=new JSONObject(jsonString);
JSONObject obj4=null;
//Getting all the keys inside json object with keys- from and to
Iterator<String> keys= obj3.keys();
while (keys.hasNext())
{
String keyValue = (String)keys.next();
obj4 = obj3.getJSONObject(keyValue);
//getting string values with keys- from and to
String from = obj4.getString("from");
String to = obj4.getString("to");
int hourstart = Integer.parseInt(from);
int hoursclose = Integer.parseInt(to);
System.out.println("From : "+ hourstart +" To : "+ hoursclose);
}

Related

get value by key jsonarray

JSONArray arr =
[
{"key1":"value1"},
{"key2":"value2"},
{"key3":"value3"},
{"key4":"value4"}
]
arr.get("key1") throws error. How can I get the value by key in JSONArray?
arr.getString("key1") also throws error. Should I loop through the array? Is it the only way to do it?
What is the error?
In Eclipse Debug perspective, these expressions returns as; error(s)_during_the_evaluation
You can parse your jsonResponse like below code :
private void parseJsonData(String jsonResponse){
try
{
JSONArray jsonArray = new JSONArray(jsonResponse);
for(int i=0;i<jsonArray.length();i++)
{
JSONObject jsonObject1 = jsonArray.getJSONObject(i);
String value1 = jsonObject1.optString("key1");
String value2 = jsonObject1.optString("key2");
String value3 = jsonObject1.optString("key3");
String value4 = jsonObject1.optString("key4");
}
}
catch (JSONException e)
{
e.printStackTrace();
}
}
Sounds like you want to find a specific key from an array of JSONObjects. Problem is, it's an array, so you have to iterate over each element. One solution, assuming no repeat keys is...
private Object getKey(JSONArray array, String key)
{
Object value = null;
for (int i = 0; i < array.length(); i++)
{
JSONObject item = array.getJSONObject(i);
if (item.keySet().contains(key))
{
value = item.get(key);
break;
}
}
return value;
}
Now, let's say you want to find the value of "key1" in the array. You can get the value using the line: String value = (String) getKey(array, "key1"). We cast to a string because we know "key1" refers to a string object.
for (int i = 0; i < arr.length(); ++i) {
JSONObject jsn = arr.getJSONObject(i);
String keyVal = jsn.getString("key1");
}
You need to iterate through the array to get each JSONObject. Once you have the object of json you can get values by using keys
You can easy get a JSON array element by key like this:
var value = ArrName['key_1']; //<- ArrName is the name of your array
console.log(value);
Alternatively you can do this too:
var value = ArrName.key_1;
That's it!

Get JSON keys with values

I have been trying to get the key and value of my JSONObject. I have no idea why this isn't working, because String key is clearly a string?
My code:
JSONObject obj = new JSONObject(historie2.getData());
Iterator<?> keys = obj.keys();
while(keys.hasNext()) {
String key = (String)keys.next();
String value = obj.getString(key); //This is where the error comes
}
The JSONObject:
{
"relatie_website": ["www.apple.com"],
"relatie_kvknummer": ["NL3234234"],
"relatie_naam": ["Apple international inc."],
"relatie_d400code": [null],
"relatie_zoeknaam": ["APPLE INC"],
"relatie_debiteurnummer": ["3523523"],
"relatie_btwnummer": ["332342"]
}
This is the error I have been getting:
org.json.JSONException: JSONObject["relatie_website"] not a string.
You should change your object to be sth like that :
{
"relatie_website": "www.apple.com",
"relatie_kvknummer": "NL3234234",
"relatie_naam": "Apple international inc.",
"relatie_d400code": null,
"relatie_zoeknaam": "APPLE INC",
"relatie_debiteurnummer": "3523523",
"relatie_btwnummer": "332342"
}
Because the problem is that your values are an array and not a string.
But if you need te keep your values in an array you can change your code to support the arrays :
JSONObject obj = new JSONObject(historie2.getData());
Iterator<?> keys = obj.keys();
while(keys.hasNext()) {
String key = (String)keys.next();
JSONArray value = obj.getJSONArray(key);
}
And you will have a JsonArray that you can manipulate as you want by doing sth like that :
for (int i = 0; i < value.length(); i++) {
String val = value.getString(i).toString();
logger.info("val : " + val);
}

How to parse JSON structured-JSON Array Object in Java

i'm trying to parse this JSON code
{
"resultCode":"350",
"message":"OK",
"result":1,
"data":
{
"totalCount":"2",
"videos":[
{
"videoId":"73bfedf534",
"VideoUrl":"www.videourlexample.com",
"title":"vbsample1",
"description":""
},
{
"videoId":"73bfedf534",
"VideoUrl":"www.videourlexample.com",
"title":"vbsample2",
"description":""
}
]
}
}
I was able to parse only this.
"resultCode":"350",
"message":"OK",
"result":1,
this is the java code
JSONObject jsonObject = (JSONObject)
//return the JSON code above.
jsonParser.parse(getHTML("...httpRequest..."));
// get a String from the JSON object
String resultCode = (String) jsonObject.get("resultCode");
System.out.println("[RESULTCODE] The message is: " + resultCode);
// get a String from the JSON object
String message = (String) jsonObject.get("message");
System.out.println("[MESSAGE] The message is: " + message);
// get a number from the JSON object
long result = (long) jsonObject.get("result");
System.out.println("[RESULT] The resultCode is: " + result);
I can't parse the "data". Someone can help me?
I would like to take each value from the json array separately... like resultCode, message and result.
Thank you.
JSONObject mainObj= new JSONObject(yourJSON);
String resultCode= mainObj.get("resultCode");
String message= mainObj.get("message");
String result= mainObj.get("result");
JSONObject dataObj = mainObj.get("data");
JSONArray jsonArray = (JSONArray) dataObj.get("videos");
for (int i = 0; i <jsonArray.length(); i++) {
JSONObject obj= jsonArray.get(i);
String videoId=obj.get("videoId");
String videoUrl=obj.get("VideoUrl");
String title=obj.get("title");
String description=obj.get("description");
System.out.println("videoId="+videoId +"videoUrl="+videoUrl+"title=title"+"description="+description);
}
System.out.println("resultCode"+resultCode+"message"+message+"result"+result);
You can try using this:-
JSONObject dataObj = (JSONObject)dataObj .get("data");
JSONArray jsonArray = (JSONArray) dataObj.get("videos");
for (int i = 0; i <jsonArray.length(); i++) {
System.out.println(((JSONObject)jsonArray.get(i)).get("videoUrl"));
}
Currently I have just printes videoUrl, you can similarly get other attributes for videos.
for data use:
int totalCount = (int) ((Map) jsonObject.get("data")).get("totalCount");
JSONArray videos = (JSONArray) jsonObject.get("data")).get("videos");
and then parse videos JSONArray.

Convert a String to HashMap

I am getting this string from a service. I want a map or json out of this. It should look like this.
Map output
Total time taken:226006
nodea:10615
nodez:5308'
String timingTrace = "Total time taken:226006.,"
+ "time spent in nodes:{\"nodea\":{\"timeTaken\":10615},\"nodez\":{\"timeTaken\":5308}}\"";
What I have tried so for is the below code. Can I do something better? Any library that can easily convert the above string to map.
if (timingTrace != null) {
arrayofTimeStamp = StringUtils.splitByWholeSeparator(StringUtils.remove(timingTrace, " "), ".,");
}
String[] totaltime = StringUtils.split(arrayofTimeStamp[0], ":")
Map<String,Object> timestamps = new HashMap<String, Object>();
timestamp.put(totaltime[0], totaltime[1]);
String[] nodetimestamp = StringUtils.splitByWholeSeparator(arrayofTimeStamp[1], "time spent in nodes:");
getMapped(nodetimestamp[1]);
public void getMapped(String json) throws JSONException, ParseException {
JSONObject obj = new JSONObject(json);
Iterator<String> keys = obj.keys();
while (keys.hasNext()) {
String key = keys.next();
String timetaken = JsonPath.read(json, "$." + key + ".timeTaken");
timestamp.put(key, timetaken);
}
}
You are using timestamp Map<> object in function getMapped(String json) that give you error because you haven't passed it you declare in function.
To get output you have mention change write below code instead of function getMapped(String json) :
JSONObject obj = new JSONObject(nodetimestamp[1]);
Iterator<String> keys = obj.keys();
while (keys.hasNext())
{
String key = keys.next();
String timetakenStr = obj.getString(key);
JSONObject child = new JSONObject(timetakenStr);
timestamps.put(key, child.getString("timeTaken"));
}
Using above code your Map<> will contain same what you mention.
OutPut :
{nodea=10615, Total time taken=226006, nodez=5308}

How separate keys and values in this JSON object, using Java?

I have JSON object like
{
"projector":"no",
"video_conference":"no",
"polycom":"no",
"lcd":"no",
"digital_phone":"no",
"speaker_phone":"no"
}
How do I store the keys in one array and the values in a separate array?
Try GSON for converting your java object to json and vice versa.
Refer this link
http://code.google.com/p/google-gson/
You may try this.
String s = " { "projector":"no", "video_conference":"no", "polycom":"no", "lcd":"no", "digital_phone":"no", "speaker_phone":"no" }";
JSONObject jObject = new JSONObject(s);
JSONObject menu = jObject.getJSONObject("projector");
Iterator iter = menu.keys();
String[] keyArr = new String();
String[] valArr = new String();
int count = 0;
while(iter.hasNext()){
keyArr[count] = (String)iter.next();
valArr[count] = menu.getString(key);
count +=1;
}
I like Jackson from http://codehaus.org/ for JSON parsing.
String text = "{ \"projector\":\"no\", \"video_conference\":\"no\", \"polycom\":\"no\", \"lcd\":\"no\", \"digital_phone\":\"no\", \"speaker_phone\":\"no\" }";
ObjectMapper mapper = new ObjectMapper();
Map<String,Object> map = mapper.readValue(text, Map.class);
Set<String> k = map.keySet();
Collection<Object> v = map.values();
String[] keys = k.toArray(new String[k.size()]);
String[] values = v.toArray(new String[v.size()]);

Categories

Resources