Dynamic Creation of JSON Object Arrays - java

This is a continuation of my work on a gradebook program. I have been posting my questions related to JSON and connecting two applications to StackOverflow because I've been having a really difficult time with that part.
I have been attempting to create an HTTP POST request that uses JSON for the purpose of sending information from a Java gradebook application to a Rails web-based application that displays those grades in the form of a report to students.
Ultimately, I want to send more than just one student's information. Furthermore, each student might have anywhere from 0 to 50 assignments, descriptions of the assignments, as well as grades for those assignments. On top of that there will be multiple classes/courses of students. All this information needs to be "read in" to the JSON object. Does anyone have any suggestions about how I could modify this code so that I could send all that data?
The farthest that I was able to take the JSON-related part of code is shown below. However, that code needs to be modified as the following questions suggest.
1. How do I create the array of JSON objects dynamically rather than how it is shown below (since the courses, students, and grades will vary and be read in from the Java program)?
2. How do I synthesize/combine the three JSON arrays of objects below to make it work? My idea is that I write the array of course objects then somehow embed the array of student objects as part of each course object, then somehow embed the array of grade objects as part of each student object.
{‘JSONArrayOfCourseObjects’ : [{‘courseID’ : ‘Botany101FallSemester’, ‘courseInstructor’ :
‘Mr. Smith’}, {‘courseID’ : ‘Physics101FallSemester’, ‘courseInstructor’ : ‘Mrs. Newton},
etc.]}
{‘JSONArrayOfStudentObjects’ : [{‘Name’ : ‘John Doe’, ‘StudentID’ : ‘12345678’, ‘Address’ :
‘1234 Main Street’}, {‘Name’ : ‘Don Corleone’, ‘StudentID’ : ‘87654321’, ‘Address’ :
‘121 Walberry Ave’}, etc.]}
{‘JSONArrayOfGradeObjects’ : [{‘nameOfAssignment’ : ‘Irrigation Homework 1’,
‘dateOfAssignment’ : ‘Sept 1, 2014’, ‘categoryOfAssignment’ : ‘Homework’},
{‘nameOfAssignment’ : ‘Test 1’, ‘dateOfAssignment’ : ‘Sept 14, 2014’, ‘categoryOfAssignment’ :
‘Test’}, etc.]}

JSONlib is the simplest Java API out there for generating quick and dirty JSON. It has everything you need to build up the object and convert it to text. If you need something more powerful, there's GSon and Jackson.
Here are some samples. This example is in Groovy so it's not copy and pasteable, but it shows you how to use it:
def array = new JSONArray()
new File("/path/to/grades/files").eachFile { file ->
String rawJson = file.text
JSONObject obj = (JSONObject ) JSONSerializer.toJSON( rawJson )
array = array.element(obj)
})
println array.toString(5) //Use 5 character indentation

Related

Getting a JSON Array from JSON Object (SOLVED)

First time having to work with JSON data on my own, even if very simple.
Here is the JSON data I'm working with:
{
"heart" : [92, 108],
"temperature" : [85.08, 85.66],
"conductance" : [4095, 4095]
}
What I'm attempting to do is extract one of the three arrays found within that JSON object, but I'm receiving a JSONException: Not a primitive array: class org.json.JSONArray. Here is a portion of the code that I'm using to extract the array of values associated with "heart":
JSONObject obj = new JSONObject(obtainJSONObject());
JSONArray arr = new JSONArray(obj.getJSONArray("heart")); // This is where the error is occuring
int low = arr.getInt(0);
int high = arr.getInt(1);
I've tried to follow what this solution answered, but can't really make much sense of it: How to Get JSON Array Within JSON Object?
I'm not sure if it has something to do with the way how the JSON data is being formatted? I did check online to see if it was any valid or not at https://jsonformatter.curiousconcept.com/. Any help or insights will be greatly appreciated!

REST services PATCH API example

I am trying to call the REST Webservices PATCH API, here is My JSON payload
[
{ "op":"replace", "path":"/values/Timestamp","value":"2016-10-28T15:25:43.511Z"},
{ "op":"replace", "path":"/values/Flag", "value":true },
{ "op":"replace", "path":"/values/Flow", "value":"Flow A"},
{"op":"replace", "path":"/values/Interests", "value":[ "Sports", "Book Reading" ] }
]
JSON Value attribute has different values with different data types. and I want to prepare Entity object(Java) and convert it into JSON and call REST end point.
now
I am not very sure
which is the best suitable data type I can choose for values attribute
I have referred following links but I didn't get enough details
Android REST API using PATCH method
https://www.rfc-editor.org/rfc/rfc5789#section-2.1
http://blog.earaya.com/blog/2013/05/30/the-right-way-to-do-rest-updates/
http://williamdurand.fr/2014/02/14/please-do-not-patch-like-an-idiot/
but I didn't get enough details.
any suggestion on this is really appriciated
Got the java object from the client and created another Java class with below properties and set the values
opn - string
path - String
value - Object
added above java objects to array list then used the GSON library to convert it into the array of JSON objects which will be accepted by patch api.
and please note the content type is application/json-patch+json

How to write my own JSON parser?

I want to write a JSON parser that parses input JSON of depth n for college assignment.
As far as I have understood, I will have to convert this JSON into <String, Object> map and then create classes out of it.
Is this correct? also How would I come to know exact datatypes of the values in JSON?
for ex my sample JSON sis.
{
“name”: “user”,
“address”: {
"city":"abc",
"zip":12345
}
}
Then I am supposed to create a class named say User that has to fields
1. name: String 2. Adderss : Object
and Address class having city : string and zip :int with getters and setters.
Is this correct? How to dynamically create a class?
How should I start ?
see this for that (not recommended): Creating classes dynamically with Java.
Advice of #T.J.Crowder is a good one: some collection.
public class json_java{
Map<String,Object> values=new HashMap<String,Object>;
To get the type:
JSONObject one_object=...
Object one_value = one_object.get("city");
one_value.getClass().getName(); // => String

Serializing as javascript object

I am working on a Spring MVC and I want to insert javascript into the html output for analytics purpose. I am only partially familiar with serialization but I figured it does the job nicely rather than manually constructing a string containing javascript.
Would it be possible to generate something the following snippet? Any pointers would be great!
"emd" : new Date('6/6/2014')
Update:
I need to output a javascript object which has many fields which may be complex. Hence, on the backend I am gathering all the data into java beans with all the information and I plan to use Jackson mapper to convert to string that I can just output through JSP.
Generating the above snippet does not seem straightforward though, not sure if it is even possible. For context, the rest of that javascript looks something like this.
Analytics.items["item_123"] = {
//ratings and reviews
"rat" : a.b, //the decimal value for the rating
"rev" : xxxx, //integer
//list of flags that indicate how the product was displayed to the customer
//add as needed...tracking code will pick up flags as needed when they are available
"dec" : ["mbe", "green", "recycled"],
//delivery messaging
"delivery" : {
"cd" : new Date() //current date
"offers" : [{
"type" : "abcd"
"emd" : new Date('6/6/2014'),
"weekend" : true
}
]
},
};
JSON.stringify should do the trick. It will be built into your browser, unless you're using a very old browser, in which case you can use a polyfill.

Workaround on Scraping HTML by diving into js source code

I learn about jSoup recently and would like to dive more into it. However, I have met obstacle handling webpages with javascript (I have no knowledge in js, yet :/).
I have read that htmlunit would be the correct tool to perform webbrowser actions, but I figured out that I would need no knowledge in js if I can find out the JSON object obtained in the webpage using the javascript.
For example, this page:
among the source files, one of them is tooltips.js. In this file, variable rgNeededFeeds is generated and called in method LoadHeropediaData(), which is the method to generate the whole URL link for getting the json object.
URL = URL + 'jsfeed/heropediadata?feeds='+strFeeds+'&v=3633666222511362823&l=english';
I could not get my mind on what is actually strFeeds. I have tried various combinations but it doesn't work (it returned an empty array...). Or, my guess is totally off?
What I actually need is the data it displays on top when you click on one of the "items". The info in the "hover" would do too, but it lack the "recepi" info. And I'm presuming that by getting the json object from the full URL above, well, basically all data infos should be in that json.
Anyways, this is only based on what I understand from staring at those source files for hours. Do correct me if I'm wrong. (I'm in Java by the way)
**p/s: I would also like to take this opportunity to express my thanks to Balusc, he has been everywhere when I have doubts on jSoup. :>*
strFeeds is nothing but one of these two strings : itemdata or abilitydata
You can find this in tooltips.js at line 38-45
var rgNeededFeeds = [];
$.each( [ 'item', 'ability' ],
function( i, ttType ){
icons = GetIconCollection( ttType );
if ( icons.length ){
rgNeededFeeds.push( ttType+'data' );
//..............
}
}
)
ttType is the value of an iteration over the array [ 'item', 'ability' ] which concatenated with the string data is pushed into the array rgNeededFeeds
The function LoadHeropediaData is called at the end of the function above with rgNeededFeeds as parameter :
LoadHeropediaData( rgNeededFeeds );
Aside note : If you begin to start scraping websites, learning javascript will be MANDATORY.
NOTE : you're right, the JSON contains all the information needed...

Categories

Resources