Reading a JSON with multiple different classes as a response - java

So I'm working on a windows app to practice my coding and expand my knowledge and I'm having a big issue working with the JSON from Riot Games. I'm not really sure the terminology to look up because I've never learned how to work with JSON so I've been making fair progress using google-fu and stack-overflow as references, along with various documentation.
I received all the following data using inputstream and outputstream. But it's all as an unformatted JSON, no indents and really hard to read. I assume I used the wrong tool for the task here and it just read characters and printed them.
My question is this, what syntax should I be looking at to import a JSON from a URL to a JSON file. Then what should I look at to convert or read that JSON as multiple different Java objects so that I may use the data in my code.
Using Gson is an option I've explored already but I'm not comfortable with their syntax, and I'd rather steer clear of more 3rd party dependencies if i can help it.
Any idea's or discussion is welcome, I'm a little over my head with the JSON here so any discussion i can learn from would help.

Despite your aversion of third party libraries, I would strongly consider looking into the Jackson library for java, and utilizing its deserialization/serialization features.
Essentially, you create java objects that can be mapped from JSON. For example, for the JSON:
{
"email": "email#gmail.com",
"googleId": "43243243242432",
"name": "some name"
}
Create a java class:
public class User {
private String email;
private String googleId;
private String name;
// Getters and Setters...
}
You can then map the JSON String to the object, using Jackson's object mapper, e.g.:
ObjectMapper mapper = new ObjectMapper();
User user = mapper.readValue(myJsonString, User.class);
This allows you to easily access the fields:
String name = user.getName(); // some name
String email = user.getEmail(); // email#gmail.com
and so on.

If you want to do this entirely in Java just skip to the bottom. I was thinking of using Java Script at first. But, realized you might not want to do that half way through.
To get a JSON file from a URL you will most likely need to use Java Script. And in that vain JQuery, a tool for Java Script, has a function for this. See .getJSON(). If you really don't want to use any third parties it can be done in native javascript see https://stackoverflow.com/a/2499647/1361042. However, using JQuery is probably much easier.
$.getJSON('url', function(data) {
//data is the JSON
});
Then you write the data(a JSON object) to a JSON file. This file can then be used in your Java, where the JSON file will be imported and used as a JSON object that you can convert to Java objects.
JSON objects are basically Java Script objects with a little bit different formatting. Java objects are in a different format from Java Script objects. So you will need to do some conversion. This questions touches on that.
Convert a JSON string to object in Java ME?
Java
However, it might be easier for you do this entirely in Java, if that's your strong point. If you want to do it entirely in Java the top part is pretty irrelevant.
This is what I found on Java being used:
simplest way to read json from a URL in java

Related

Validate JSON before further processing

I have the following csv file (In production the number of records can range from 20k-100k and has many fields )
id,firstname,lastname,email,profession
100,Betta,Wandie,Betta.Wandie#gmail.com,developer
101,Janey,Firmin,Janey.Firmin#gmail.com,doctor
I need to convert this to json and do further processing.
CSV->JSON->PROCESS FURTHER
.I am able to convert it to JSON directly using the code given here
directly convert CSV file to JSON file using the Jackson library
But i want do validations for json like if lastname has null value then ignore that record or id is missing then ignore that record.
How can i handle the validation?I am using Java 8 and spring boot latest version
I have done something similar by using JavaScript (Nashorn). Yes, that is nasty, but it works, and it is astonishingly fast!
Unfortunately, I do not have the source code at hand …
Why I did it that way had the same reasons as #chrylis-on strike implies in their comment: the validation is much easier if you have an object for each JSON record. But as I was lazy, and there was definitely no need for the Java object I had to create for this, I had the idea with the JavaScript script inside my Java program.
Basically, a JSON String is the source for a JavaScript program; you can assign it directly to a JavaScript variable and then you can access the records as array elements and the fields by their name. So your JavaScript code walks through the records and drops those that do not match your validation rules.
Now the Java part: the keyword here is JSR223; it is an API that allows you to execute scripts inside your Java environment. In your case, you have to provide the converted JSON in the context, then you start the script that writes the modified JSON back to the context.
If the converted JSON is too large, you can even use the same technique to check record by record; if you compile the script, it is nearly as fast as native Java.
You can even omit Jackson and let JavaScript do the conversion …
Sorry that I cannot provide code samples; I will try to get hold on them and add them if I get them.

Java JSON editor / visualizer

I wrote an application that takes a JSON file as configuration. Up to this point, I wrote the JSON config by hand. However, now I want to allow other users who are not familiar with JSON format to make their own configurations. There's only 3 types of objects that the configuration needs to store, but the user should be allowed to add multiple copies of these objects. I want to write a configuration application where the user can press a button such as "Add Type A" and an object of type A is populated with default values and visualized so that the user can select properties and edit them. I know how to write an application that does this, but I feel like I'm re-inventing the wheel. Does anyone know of an open-source Java library that I can use inside my config application to handle visualization and editing a JSON file? If I'm approaching this from completely the wrong direction, please let me know.
I'm tempted to say "don't fear to reinvent the wheel".
But the fact is that there a bunch solutions available :
How do I convert an object to JSON representation (and vice-versa)
Java representation of JSON Object
Javascript to Java using JSON
among them, GSON looks fine.
For my personal experience, Yaml turned out to be an appropriate solution.

WebService - Overview

There's a lot of info out there for a newbie like myself when it comes to webservices, I acknowledge that.
However, most of the Google results I've seen tend to be focusing on a specific format or strategy, and all of them different to each other.
As a newbie, I am looking to get more of an overview of the various options open to me, their pros & cons... before I start committing to a specific one.
For example, I have an existing webservice created from a SQL Server source via ASP.net and this by default comes out as a DiffGram. So there are articles that tell me how to parse the diffgram data coming into my Android app, but I still do not know if the diffgram is the best option I should be using in the first place.
Should I, for example be changing my webservice to output JSON ?
Does anyone know of a 101 level tutorial or explanation out there ?
Many Thanks
DiffGram is just another type of XML format. In order to parse the XML data in Android, simply use the XMLFullParse class.
FYI: http://developer.android.com/training/basics/network-ops/xml.html
However if you just want to create a simple data exchange WebService, Json is definitely a better choice. Json is simple, lightweight, easier-to-parse and surely easier to use.
Example:
JsonObject json = new JsonObject(jsonString);
json.put("name", "Michael");
json.put("age", "18");
String name = json.opt("name");

Send ArrayList over the network - Convert Java ArrayList to XML String

I'm new to Java. I want to send an array (ArrayList) of objects over the network via Java Web Service to my Silverlight app. This ArrayList contains custom class objects:
ArrayList<SVNSearchResult> results
so I'm thinking the best way is to serialize this to an XML String and on the Silverlight part, use LinQ to parse it. If there's a better way to send it please let me know. Thanks.
XML is a good fit for this. JSON would be one of the other usual suspects these days.
Whatever format you end up choosing, make sure you get the encoding right.
For a starter, try JSON. It has a network-efficient format, and is supported by any major language in the world.
XML is only my second choice as it is more complicated to generate/parse and is more verbose.

How to deserialize in PHP an object serialized in Java

Is there any way to deserialize in PHP an object serialized in Java? IE If I have a Java class that implements Serialization and I use an ObjectOutputStream to write the object, and convert the result to a string, is there a way in PHP to take that string and create a similar object representation from it?
What does the Java Serialized data look like?
Response:
���sr�com.site.entity.SessionV3Data���������xpsr�java.util.HashMap���`��F�
loadFactorI� thresholdxp?#�����w������t� sessionIdt�0NmViMzUxYWItZDRmZC00MWY4LWFlMmUtZjg2YmZjZGUxNjg5xx
:)
I would heavily recommend you don't do this. Java serialization is meant for a Java instance to both save and load the data (for either transmission to another Java application or persistence between invocations of the same application). It was not at all meant to be a cross-platform protocol.
I would advise you to make an API adapter layer between the two. Output the contents of your Java object to a format you can work with in PHP, be it XML, YAML, or even a binary format (where you could use DataOutputStream).
What is the easiest way to eat soup with chopsticks when the soup was put in a bowl with a ladle? Put the soup in a cup and discard your chopsticks, because chopsticks are a poor choice for aiding in the consumption of soup. A cup (ubiquitous) eliminates external dependencies except for "mouth" and "opposable thumbs", both of which come with the standard library of humans.
A more elegant solution would be to encode that Java object with a JSON Serializer or XML serializer. Protocol Buffers or any other intentionally cross-language serialization technique would work fine plus Protocol Buffers can efficiently encode binary data.
Some time ago i did something simillar. However i didn't make PHP read "Java serialize" format. I did the oposite, that is, made Java serialize itself to a "PHP serialize" format. This is actually quite easy. Have look at PHPSerializedResponseWriter class that is a part of Solr package:
https://github.com/terrancesnyder/solr-analytics/blob/master/solr/core/src/java/org/apache/solr/response/PHPSerializedResponseWriter.java
...then all you have to do is just read the string and call:
$result = unserialize($string);
From comments in the online PHP manual, there is a Java class that serializes to the PHP serialization format that you can look into. Then you can unserialize the data using the standard PHP functionality.
Is it possible to use one of the more common cross platform data formats like JSON to communicate between your Java app and PHP? PHP has plenty of parsers for those formats. Check out json_decode for an example.
Is there any way to deserialize in PHP
an object serialized in Java?
Yes. The question is, should you? Exporting the Java object as XML or JSON probably makes more sense.
The following SO question might also help.
Dynamically create PHP object based on string

Categories

Resources