Obtaining JSON object values by name Java - java

My JSON Data looks something like this:
[
"{\"pid\":\"1\",\"title\":\"New CEO announced\",\"titleirish\":\"CEO nua\",\"content\":\"Bernard Byrne has been announced as the new CEO. Rejoice!\",\"contentirish\":\"Is Bernard Byrne an CEO. B\\\\u00edg\\\\u00ed s\\\\u00e1sta!\",\"imageurl\":\"http:\\\\\\/\\\\\\/scoiluiriada.ie\\\\\\/wp-content\\\\\\/uploads\\\\\\/2014\\\\\\/02\\\\\\/IMG_1781-150x112.jpg\",\"category\":\"News\",\"publishedby\":\"Andy\",\"modified\":\"2015-07-01 16:21:13\",\"buildings\":\"Bankcentre,Hume House,Time House\"}",
"{\"pid\":\"2\",\"title\":\"New CTO pronounced\",\"titleirish\":\"CEO nua\",\"content\":\"Bernard Byrne has been announced as the new CEO. Rejoice!\",\"contentirish\":\"Is Bernard Byrne an CEO. B\\\\u00edg\\\\u00ed s\\\\u00e1sta!\",\"imageurl\":\"http:\\\\\\/\\\\\\/scoiluiriada.ie\\\\\\/wp-content\\\\\\/uploads\\\\\\/2014\\\\\\/02\\\\\\/IMG_1781-150x112.jpg\",\"category\":\"News\",\"publishedby\":\"Andy\",\"modified\":\"2015-07-02 10:09:10\",\"buildings\":\"Hume House\"}",
....
So far I have the following code:
JSONParser parser = new JSONParser();
try {
Object obj = parser.parse(allData); // allData = JSON String above
JSONArray nitems = (JSONArray)obj;
This gives me an array of all the objects I want to parse. (it works perfectly)
Now, looping through this array, I would like to get the object member values.
Something like this:
nitems.get(0).getValueOf("title") // should return "New CEO announced"
nitems.get(0).getValueOf("titleirish") // "CEO Nua" etc.
This obviously doesn't work, what code do I use instead.
Thanks for any answers in advance.

Fixed with help from some comments. Here is solution:
JSONObject obj2 = (JSONObject)new JSONParser().parse(nitems.get(i).toString());
System.out.println(obj2.get("title").toString());

Related

Parsing JSON in Java Using org.json

I have a large file with many JSON objects similiar to the following. I need to parse everything to get the "bought_together" items as an array using the org.json library. I'm having trouble accessing anything nested in "related".
What is the required code to retrieve "bought_together" as a list?
{
"asin": "11158732",
"title": "Girls Ballet Tutu Zebra Hot Pink",
"price": 3.17,
"imUrl": "http://ecx.images-amazon.com/images/I/51fAmVkTbyL._SY300_.jpg",
"related":
{
"also_bought": ["L00JHONN1S", "B002BZX8Z6"],
"also_viewed": ["F002BZX8Z6", "B00JHONN1S", "B008F0SU0Y", "B00D23MC6W", "B00AFDOPDA"],
"bought_together": ["D202BZX8Z6"]
},
"salesRank": {"Toys & Games": 211836},
"brand": "Coxlures",
"categories": [["Sports & Outdoors", "Other Sports", "Dance"]]
}
Here is my attempt (Please note, this is within a MapReduce program so some lines may seem out of context.):
JSONObject object = new JSONObject(sampleText); //sampleText is json that has been split by line
JSONArray boughtTogether = new JSONArray(object.getJSONArray("bought_together"));
using the following code, I hope it's help you.
//this will be your json object that contains and convert your string to jsonobject
//if you have json object already skip this.
JSONObject yourJSON = new JSONObject(targetString);
//getting the "related" jsonObject
JSONObject related = yourJSON.getJSONObject("related");
//getting the "bought_together" as an jsonArray and do what you want with it.
//you can act with jsonarray like an array
JSONArray bought_together = related.getJSONArray("bought_together");
//now if you run blow code
System.out.print(bought_together.getString(0));
//output is : D202BZX8Z6
-------update according to update the question------
you should change your code like this:
JSONObject object = new JSONObject(sampleText); //sampleText is json that has been split by line
JSONObject related = object.getJSONObject("related");
JSONArray boughtTogether = related.getJSONArray("bought_together");
-------update-------
i think you need to this point (it's not technicality all of they difference)
every thing are in {} , they will be JSONObject and the relation
is key and value like :
{"name":"ali"}
this is a jsonobject and the value of key "name" is ali and we call it
like:
myJsonObject.getString("name");
every thing are in [] ,they will be JSONArray and the relation is
index and value like :
["ali"]
this is a JsonArray the value of index 0 is ali and we call it
like:
myJsonArray.getString(0);
so in your case:
your total object is a JSONObject
the value of "related" key is still a JSONObject
the value of "bought_together" key (which is inside the value of {jsonobject} "related" key) is a JSONArray

Jettison JSON/java , send list of string with json request

I am creating JSON object and send over the network , like
org.codehaus.jettison.json.JSONObject json = new org.codehaus.jettison.json.JSONObject();
json.put("id", "15");
json.put("code", "secret");
json.put("type", "new type");
Also I have links of photos what I want to put into this JSON
my links like http://box.com/images/photo.jpg,http://box.com/images/photo1.jpg
http://box.com/images/photo2.jpg, http://box.com/images/photo3.jpg
As I understand I must have some list/array and put like
json.put("images", links)
How to do it, put and parse... I need one key, and list of values.
Is JSON array is useful for this?
Thanks
Yes. JSONArray is what you need.
List <String> links = getLinks();
JSONArray array = new JSONArray();
for (String link : links)
array.put(link);
JSONObject obj = new JSONObject();
//put id, code, type...
obj.put("images", array);
Check out the JSONArray class.
http://jettison.codehaus.org/apidocs/org/codehaus/jettison/json/JSONArray.html
You'll create a JSONArray and use that in your put command.

Convert object to JSON without escapings on strings

I have searched the web for answer and everywhere is done like this:
JSONObject params = new JSONObject();
Gson gson = new Gson();
params.put("Event", gson.toJson(myEvent));
But this is returning me Json like this with all escapings on ":
"Event":"{\"Test1\":\"TestValue1\",\"TestObj\":{\"Test2\":\"TestValue2\",\"Test3\":\"TestValue3\"...
How can I have Json free of all escapings, just like this:
"Event":"{"Test1":"testValue1","TestObj":{"Test2":"testValue2","Test3":"testValue3"...
Cheers mates.
I can pass the object like this, property by property:
createEvent.put("Test1", myObj1.Test1);
createEvent.put("Test2", myObj2.Test2);
and pass the Json to api, but Notes is with escapings:
String myNoteListJson = new Gson().toJson(myNoteList);
createEvent.put("Notes", myNoteListJson);
I found an answer, here it is:
I am passing property by property:
createEvent.put("Test1", myObj1.Test1);
createEvent.put("Test2", myObj2.Test2);
and the Notelist problem is solved like this:
JSONArray mJSONArray = new JSONArray(myNoteList);
createEvent.put("Notes", mJSONArray);

How to parse this JSON string

I'm trying to parse this string into java, but I keep getting errors.
{"id":1,"jsonrpc":"2.0","result":{"limits":{"end":3,"start":0,"total":3},"sources":[{"file":"/media/storage/media/re Music/","label":"re Music"},{"file":"/media/storage/media/ra Music/","label":"ra Music"},{"file":"addons://sources/audio/","label":"Music Add-ons"}]}}
When I use this code ...
String temp = //json code returned from up above
JSONObject obj = new JSONObject(temp);
JSONArray array = obj.getJSONArray("sources");
I get an error saying org.json.JSONObject Value... and then displays what is in temp. Any help?
The array named "sources" is several levels deep. You need to traverse down into the json.
Code formatters help with this stuff...
http://jsonformatter.curiousconcept.com/
{
"id":1,
"jsonrpc":"2.0",
"result":{
"limits":{
"end":3,
"start":0,
"total":3
},
"sources":[
{
"file":"/media/storage/media/re Music/",
"label":"re Music"
},
{
"file":"/media/storage/media/ra Music/",
"label":"ra Music"
},
{
"file":"addons://sources/audio/",
"label":"Music Add-ons"
}
]
}
}
It looks like the "sources" array is in the "result" object. So you would need to get that object and then get the array from that like this:
JSONObject obj = new JSONObject(temp);
JSONObject result = obj.getJSONObject("result");
JSONArray array = result.getJSONArray("sources");
Your json should have top level object, from there you need to get child objects. See this link for more detail.

java code corresponding to Newtonsoft.Json.JsonConvert.SerializeObject(Object source,Newtonsoft.Json.JsonSerializerSettings()) in .net?

I have a code in .net that serializes a request to the json format ... The code is something like this.
var ops = new Newtonsoft.Json.JsonSerializerSettings();
ops.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore;
ops.MissingMemberHandling = Newtonsoft.Json.MissingMemberHandling.Ignore;
ops.DefaultValueHandling = Newtonsoft.Json.DefaultValueHandling.Ignore;
ops.Converters.Add(new Newtonsoft.Json.Converters.JavaScriptDateTimeConverter());
String strSO = Newtonsoft.Json.JsonConvert.SerializeObject(source,
bIndent ? Newtonsoft.Json.Formatting.Indented : Newtonsoft.Json.Formatting.None,
ops);
I tried the java code corresponding to this portion but it doesn't work.
From my understanding, the Newtonsoft serializer takes an object with member variables and outputs a json string that represents that object.
So you can do something like:
Product product = new Product();
product.Name = "Apple";
product.Expiry = new DateTime(2008, 12, 28);
product.Price = 3.99M;
product.Sizes = new string[] { "Small", "Medium", "Large" };
string output = JsonConvert.SerializeObject(product);
And you'll get an output string like:
{"Name": "Apple",
"Expiry": "\/Date(1230375600000+1300)\/",
"Price": 3.99,
"Sizes": ["Small", "Medium", "Large"]
}
Now the bad news is that the BlackBerry library that you're using doesn't use reflection to examine the structure of objects it serialises. It is a formatter rather than a serializer.
The good news is that it is pretty easy to use. The documentation is here:
http://www.blackberry.com/developers/docs/6.0.0api/org/json/me/package-summary.html
In short, to write an object such as the one above, you would do something like:
myString = new JSONStringer()
.object()
.key("Name")
.value("Apple")
.key("Expiry")
.value("Date("+myDate.getTime()+")")
.endObject()
.toString();
..and so on. Note that you are constructing the JSON structure element by element, rather than having the JSON library assume that your object is the exact structure of the data you wish to output.
Hopefully this will give you some idea of how to proceed.
If your question is "Does anyone know of a Java equivalent to Newtonsoft.Json for .NET for serializing in JSON format?"
Check the bottom of http://json.org

Categories