how to read a json file using Xtend and using MydslGenrator ,use those file in eclipse editor
First thing MydslGenrator is used to generate the code from your DSL. If you want to generate code with using JSON file use below code in MydslGenrator file
override void doGenerate(Resource resource, IFileSystemAccess2 fsa, IGeneratorContext context) {
try
{
URL url;
url = new URL("platform:/plugin/yourpackgename/foldername/yourJsonFile_Name.json");
try {
Gson gson = new Gson();
JsonReader reader = new JsonReader(new InputStreamReader(url.openStream()));
reader.beginObject();
// get your JsonObject from reader object.
// do your work here
}`
Related
I'm trying to make a program using json to save user registers to file, but when I try to read my json I get the error "JSON malformed". This is my code to write in json:
Gson gsonObject = new Gson();
FileWriter writerFile;
try {
writerFile = new FileWriter("users.json", true);
writerFile.write(gsonObject.toJson(writerUser));
writerFile.close();
} catch (IOException e) {
e.printStackTrace();
}
I use arrays to be easy modify the values (only take the json back to array and make my modify) but i can't reader this json file after writer, this is my reader code:
Gson gson = new Gson();
List<User> userList;
try {
BufferedReader readerUserList = new BufferedReader(new FileReader("users.json"));
userList = Arrays.asList(gson.fromJson(readerUserList, User[].class));
for (User user : userList) {
System.out.println(user.toString());
}
And after that i get "json malformed" error, where is my error?
If help you guys, inside my json file is my arrays like that:
[{"name":"james","idCode":1}][{"name":"kyle","idCode":2}][{"name":"test","idCode":3}]
I've never used Gson... but your json file has format problems, it is supposed to look like this:
[{"name":"james","idCode":1},{"name":"kyle","idCode":2},{"name":"test","idCode":3}]
The problem is not when you try to read, but when you write it.
I have the following code:
static void Main(string[] args)
{
HttpClient client = new HttpClient();
using (Stream stream = client.GetStreamAsync("https://opendata.rdw.nl/resource/8ys7-d773.json?kenteken=61SFSL").Result)
using (StreamReader streamReader = new StreamReader(stream))
using (JsonReader reader = new JsonTextReader(streamReader))
{
JsonSerializer serializer = new JsonSerializer();
// read the json from a stream
// json size doesn't matter because only a small piece is read at a time from the HTTP request
//What do I do here to get my one value?
}
Console.WriteLine("Press any key to continue...");
Console.Read();
}
I got this from the documentation over at the JSON.NET website. The reason being that I don't want to load the whole string, but piece by piece. The response is as follows:
[{"brandstof_omschrijving":"Benzine","brandstof_volgnummer":"1","brandstofverbruik_buiten":"6.60","brandstofverbruik_gecombineerd":"8.20","brandstofverbruik_stad":"11.10","co2_uitstoot_gecombineerd":"196","emissiecode_omschrijving":"Euro 4","geluidsniveau_rijdend":"71","geluidsniveau_stationair":"82","kenteken":"61SFSL","milieuklasse_eg_goedkeuring_licht":"70/220*2001/100B","nettomaximumvermogen":"99.00","toerental_geluidsniveau":"4125"}]
I.e., it returns an array with one json object, and I want to retrieve just one value in there, using a stream. How might I do this?
You could try the following
using System;
using System.Net.Http;
using Newtonsoft;
public class Program {
public static void Main() {
var client = new HttpClient();
var json = client.GetStringAsync("https://opendata.rdw.nl/resource/8ys7-d773.json?kenteken=61SFSL").Result;
var data = JsonConvert.DeserializeObject<dynamic>(json);
string value = data[0].co2_uitstoot_gecombineerd;
Console.WriteLine(value);
Console.WriteLine("Press any key to continue...");
Console.Read();
}
}
I made a JSON file and the I used FileOutputStream to save it as a text file in my hard drive . Then I use FileinputStream to input the file in a separated class. I use this code to print the JSON , but how can i parse it now using JSONParser .
public static void main(String[] args) throws Exception {
FileInputStream fileInputStream = new FileInputStream("D:\\XmlToJson.txt");
ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
JSONArray jsonArray = (JSONArray) objectInputStream.readObject();
ObjectInputStream is not the correct class to use here. That is to read Java objects from Java's own serialisation scheme. Has nothing to do with JSON. And why JSONParser if you don't want to parse lazy and use the parse events to build some data structure other than a JSONArray then a JsonReader is the way to go.
Slightly adapted example from the Java documentation:
public static void main(String[] args) throws Exception {
FileInputStream fileInputStream = new FileInputStream("D:\\XmlToJson.txt");
JsonReader jsonReader = Json.createReader(fileInputStream);
JsonArray array = jsonReader.readArray();
jsonReader.close();
// ...
}
Map countryList = new HashMap();
String str = "http://10.10.10.25/TEPortalIntegration/CustomerPortalAppIntegrationService.svc/PaymentSchedule/PEPL/Unit336";
try {
URL url = new URL(str);
URLConnection urlc = url.openConnection();
BufferedReader bfr = new BufferedReader(new InputStreamReader(
urlc.getInputStream()));
String line, des;
double title;
final StringBuilder builder = new StringBuilder(2048);
while ((line = bfr.readLine()) != null) {
builder.append(line);
}
// convert response to JSON array
final JSONArray jsa = new JSONArray(builder.toString());
// extract out data of interest
for (int i = 0; i < jsa.length(); i++) {
final JSONObject jo = (JSONObject) jsa.get(i);
title = jo.getDouble("NetAmount");
countryList.put(i, title);
}
System.out.println(countryList); /* Giving result if i run in Console*/
} catch (Exception e) {
// TODO: handle exception
}
renderRequest.setAttribute("out-string", countryList);
The above code is to consume JSON web services from java client. I am able to access it from java console application. But when trying with JSP or Liferay its not working. In JSP its giving java.lang.NoClassDefFoundError: org/json/JSONArray. Please help me to fix it.
Should i need to add any more jar files to the libraries to make it working in JSP?
You need to add the jar file containing JSONArray class in your web application as per this directory structure:
Tomcat_HOME
->
webapps
->
YourWebAppName
->
WEB-INF
->lib
->Here goes your jar file
Instead of using json.org.JSONArray, have you considered using Liferay's JSON API?
You can import:
import com.liferay.portal.kernel.json.JSONArray;
import com.liferay.portal.kernel.json.JSONFactoryUtil;
import com.liferay.portal.kernel.json.JSONObject;
They do something like:
JSONObject jsonObject = JSONFactoryUtil.createJSONObject(myJSONObjectString);
JSONArray jsonArray = JSONFactoryUtil.createJSONArray(myJSONArrayString);
This way there is no additional JAR required!
I am writing code that needs to extract an object literal posted to a servlet. I have studied the API for the HttpServletRequest object, but it is not clear to me how to get the JSON object out of the request since it is not posted from a form element on a web page.
Any insight is appreciated.
Thanks.
are you looking for this ?
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
StringBuilder sb = new StringBuilder();
BufferedReader reader = request.getReader();
try {
String line;
while ((line = reader.readLine()) != null) {
sb.append(line).append('\n');
}
} finally {
reader.close();
}
System.out.println(sb.toString());
}
This is simple method to get request data from HttpServletRequest
using Java 8 Stream API:
String requestData = request.getReader().lines().collect(Collectors.joining());
make use of the jackson JSON processor
ObjectMapper mapper = new ObjectMapper();
Book book = mapper.readValue(request.getInputStream(),Book.class);
The easiest way is to populate your bean would be from a Reader object, this can be done in a single call:
BufferedReader reader = request.getReader();
Gson gson = new Gson();
MyBean myBean = gson.fromJson(reader, MyBean.class);
There is another way to do it, using org.apache.commons.io.IOUtils to extract the String from the request
String jsonString = IOUtils.toString(request.getInputStream());
Then you can do whatever you want, convert it to JSON or other object with Gson, etc.
JSONObject json = new JSONObject(jsonString);
MyObject myObject = new Gson().fromJson(jsonString, MyObject.class);
If you're trying to get data out of the request body, the code above works. But, I think you are having the same problem I was..
If the data in the body is in JSON form, and you want it as a Java object, you'll need to parse it yourself, or use a library like google-gson to handle it for you. You should look at the docs and examples at the project's website to know how to use it. It's fairly simple.
Converting the retreived data from the request object to json object is as below using google-gson
Gson gson = new Gson();
ABCClass c1 = gson.fromJson(data, ABCClass.class);
//ABC class is a class whose strcuture matches to the data variable retrieved