I am trying to parse this JSONObject
{
"query": {
"yahoo:count": 1,
"results": {
"rate": {
"Name": "USD/INR",
"id": "USDINR",
"Time": "12:19pm",
"Date": "10/31/2015",
"Bid": 65.405,
"Ask": 65.43,
"Rate": 65.405
}
},
"yahoo:created": "2015-11-01T02:16:56Z",
"yahoo:lang": "en-US",
"xmlns:yahoo": "http://www.yahooapis.com/v1/base.rng"
}
}
This is my program
import java.text.ParseException;
import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class Test {
public static void main(String[] args) throws ParseException, JSONException {
String json = "{\"query\":{\"yahoo:count\":1,\"results\":{\"rate\":{\"Name\":\"USD/INR\",\"id\":\"USDINR\",\"Time\":\"12:19pm\",\"Date\":\"10/31/2015\",\"Bid\":65.405,\"Ask\":65.43,\"Rate\":65.405}},\"yahoo:created\":\"2015-11-01T02:16:56Z\",\"yahoo:lang\":\"en-US\",\"xmlns:yahoo\":\"http://www.yahooapis.com/v1/base.rng\"}}";
JSONObject json_obj = new JSONObject(json);
String Rate = json_obj.getJSONObject("query").getJSONObject("results")
.getJSONObject("rate").getString("Rate");
System.out.println(Rate);
}
}
Exception in thread "main" org.json.JSONException: JSONObject["Rate"] not a string.
at org.json.JSONObject.getString(JSONObject.java:644)
at Test.main(Test.java:16)
Could you please let me know how to resolve this ??
Its strict about its types, getString("Rate") is not a string its a number. To get the number value use getDouble("rate"). You can also use the type safe get of get("rate") which should return a Double then call toString() on it.
Isn't the stack trace obvious? Rate is not a string, but an integer. You should use getInt or getNumber or whatever is called in Java, instead of getString.
Try like this
.getDouble("Rate")
instead of
.getString("Rate")
rate is double not string
I'm working with another API which calls the google Document AI API. I'm trying to read the JSON String from the file into a Document object. How should this be done?
I tried the following but it is not working.
import com.google.cloud.documentai.v1.Document;
import java.io.FileInputStream;
Document document = Document.parseFrom(new FileInputStream("src/main/resources/responseFromAPICall.json"));
System.out.println(document.getText());
I'm getting this error:
Exception in thread "main" com.google.protobuf.InvalidProtocolBufferException: Protocol message end-group tag did not match expected tag.
at com.google.protobuf.InvalidProtocolBufferException.invalidEndTag(InvalidProtocolBufferException.java:129)
at com.google.protobuf.CodedInputStream$StreamDecoder.checkLastTagWas(CodedInputStream.java:2124)
at com.google.protobuf.CodedInputStream$StreamDecoder.readGroup(CodedInputStream.java:2358)
Today I came across this issue as well. This answer gave me the starting point for a solution.
If your json file was saved from a call to Document AI and looks like:
{
"document": {
...
"text": "...",
...
},
"humanReviewStatus": {...}
}
you may use the following code snippet:
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import com.google.cloud.documentai.v1.Document;
import com.google.cloud.documentai.v1.ProcessResponse;
import com.google.protobuf.util.JsonFormat;
Path filePath = Paths.get("src/main/resources/responseFromAPICall.json");
ProcessResponse.Builder responseBuilder = ProcessResponse.newBuilder();
JsonFormat.parser().merge(Files.newBufferedReader(filePath), responseBuilder);
Document document = responseBuilder.getDocument();
System.out.println(document.getText());
If your json file only contains the "document" object:
{
...
"text": "...",
...
}
This code will do the trick:
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import com.google.cloud.documentai.v1.Document;
import com.google.protobuf.util.JsonFormat;
Path filePath = Paths.get("src/main/resources/responseFromAPICall.json");
Document.Builder docBuilder = Document.newBuilder();
JsonFormat.parser().merge(Files.newBufferedReader(filePath), docBuilder);
System.out.println(docBuilder.getText());
I have nested JSON with bunch of children objects, but I just need response_time and question, subquestions of survey_data. What is the best way to parse nested JSON in rest controller to the object in spring?
{
"is_test_data":false,
"language":"English",
"url_variables":{
"requestId":{
"key":"requestId",
"value":"1"
}
},
"response_time":1114,
"survey_data":{
"2":{
"id":2,
"type":"parent",
"question":"For each of the following factors, please rate your recent project",
"subquestions":{
"10":{
"10001":{
"id":10001,
"type":"MULTI_TEXTBOX",
"question":"Overall Quality : Rating",
"answer":null,
}
},
"11":{
"10001":{
"id":10001,
"type":"MULTI_TEXTBOX",
"question":"Achievement of Intended Objectives : Rating",
"answer":null
}
}
}
},
"33":{
"id":33,
"type":"HIDDEN",
"question":"Submitted",
"answer_id":0,
}
}
}
Thank you.
What you should do is parse the complete json to jsonObject using json-simple jar
which create a map like structure for the json and then you can simply get the desired value from it using the key as I explained in below example
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
public class JsonDeserializer {
public static void main(String[] args) throws Exception {
File file = new File("test.json");
InputStream is = new FileInputStream(file);
StringBuilder textBuilder = new StringBuilder();
try (Reader reader = new BufferedReader(
new InputStreamReader(is, Charset.forName(StandardCharsets.UTF_8.name())))) {
int c = 0;
while ((c = reader.read()) != -1) {
textBuilder.append((char) c);
}
}
String jsonTxt = textBuilder.toString();
Object obj = new JSONParser().parse(jsonTxt);
JSONObject jo = (JSONObject) obj;
System.out.println(jo.get("response_time"));
}
}
JSON is a data communication format that is lightweight, text-based. Objects and arrays are two structured kinds that JSON can represent. A JSONArray may extract text from a String and convert it to a vector-like object. The getString(index) method of JSONArray can be used to parse a nested JSON object. This is a helper method for the getJSONString method (index). The getString() method returns a string.
Actually I am trying to parse schema.org Microdata from HTML source pages using a java library.I tried many sites finally I found any23 and Mf2j from github For .apache any23 I didn't find proper documentation so I left that and finally using Mf2j I build the project and I got the jar. I created a sample project to execute Mf2j to parse Microdata. Here is the sample code which I wrote.
package org.mypro;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.Map;
import java.util.Properties;
import java.util.Map.Entry;
import com.kylewm.mf2j.Mf2Parser;
public class MySample {
/**
* #param args
* #throws URISyntaxException
* #throws IOException
*/
public static void main(String[] args) throws IOException, URISyntaxException {
// TODO Auto-generated method stub
Mf2Parser parser = new Mf2Parser()
.setIncludeAlternates(true)
.setIncludeRelUrls(true);
URL server = new URL("http://blogbasics.com/examples-of-blogs/");
Properties systemProperties = System.getProperties();
systemProperties.setProperty("http.proxyHost","pp.xyz.com");
systemProperties.setProperty("http.proxyPort","1234");
HttpURLConnection connection = (HttpURLConnection)server.openConnection();
connection.connect();
Map<String,Object> parsed = parser.parse(new URI("http://blogbasics.com/examples-of-blogs/"));
for (Entry<String, Object> string : parsed.entrySet()) {
System.out.println(string.getKey() +" = "+string.getValue());
}
}
}
But I got output like this. I got ly image URL's but I need all Microdata metadata.
rels = {"Icon":["http://blogbasics.com/wp-content/uploads/cropped-Blog-Basics-favicon.png"],"Shortcut":["http://blogbasics.com/wp-content/uploads/cropped-Blog-Basics-favicon.png"],"apple-touch-icon-precomposed":["http://blogbasics.com/wp-content/uploads/apple-touch-icon-144x144.png","http://blogbasics.com/wp-content/uploads/apple-touch-icon-114x114.png","http://blogbasics.com/wp-content/uploads/apple-touch-icon-72x72.png","http://blogbasics.com/wp-content/uploads/apple-touch-icon-57x57.png"],"canonical":["http://blogbasics.com/examples-of-blogs/"],"external":["http://blogbasics.com","http://allisondduncan.com","http://www.kuldipsonsjewellers.com/Earring.html","http://jin6000.tumblr.com/","http://ckckarate.com","http://www.ferrypress.com/profile.php?u=Herman1879"],"nofollow":["http://bit.ly/1EQF6HG","https://curlcentric.leadpages.net/leadbox/14581e773f72a2%3A12e927026b46dc/5758142528880640/","http://blogbasics.com/examples-of-blogs/#comment-261","http://blogbasics.com","http://blogbasics.com/examples-of-blogs/#comment-262","http://allisondduncan.com","http://blogbasics.com/examples-of-blogs/#comment-270","http://blogbasics.com/examples-of-blogs/#comment-736","http://www.kuldipsonsjewellers.com/Earring.html","http://blogbasics.com/examples-of-blogs/#comment-1407","http://blogbasics.com/examples-of-blogs/#comment-3036","http://blogbasics.com/examples-of-blogs/#comment-5682","http://blogbasics.com/examples-of-blogs/#comment-6877","http://blogbasics.com/examples-of-blogs/#comment-8615","http://jin6000.tumblr.com/","http://blogbasics.com/examples-of-blogs/#comment-8684","http://ckckarate.com","http://blogbasics.com/examples-of-blogs/#comment-18326","http://www.ferrypress.com/profile.php?u=Herman1879","http://blogbasics.com/examples-of-blogs/#comment-22883","http://blogbasics.com/examples-of-blogs/#comment-26672","http://blogbasics.com/examples-of-blogs/#respond","http://www.blogbasics.com","http://www.blogbasics.com/privacy","http://www.blogbasics.com/terms-conditions/","http://www.blogbasics.com/contact/"],"publisher":["https://www.google.com/+Blogbasics"],"stylesheet":["http://blogbasics.com/wp-content/themes/tru/style.css?v=1427736009&ver=2.1.3","http://fonts.googleapis.com/css?family=Open+Sans%3A300%2C400italic%2C400%2C600%2C700%7CRokkitt&ver=1.5","http://optinskin.com/src-4/min/normalize.min.css?ver=4.3","http://blogbasics.com/wp-content/plugins/OptinSkin/skins/1/style.css?ver=4.3","http://blogbasics.com/wp-content/themes/tru/includes/lib/spyr_slidingshare/style.css?ver=0.9.3"]}
items = []
rel-urls = {"http://allisondduncan.com":{"rels":["external","nofollow"],"text":"Allison Duncan"},"http://bit.ly/1EQF6HG":{"rels":["nofollow"]},"http://blogbasics.com":{"rels":["external","nofollow"],"text":"Paul Odtaa"},"http://blogbasics.com/examples-of-blogs/":{"rels":["canonical"]},"http://blogbasics.com/examples-of-blogs/#comment-1407":{"rels":["nofollow"],"text":"Reply"},"http://blogbasics.com/examples-of-blogs/#comment-18326":{"rels":["nofollow"],"text":"Reply"},"http://blogbasics.com/examples-of-blogs/#comment-22883":{"rels":["nofollow"],"text":"Reply"},"http://blogbasics.com/examples-of-blogs/#comment-261":{"rels":["nofollow"],"text":"Reply"},"http://blogbasics.com/examples-of-blogs/#comment-262":{"rels":["nofollow"],"text":"Reply"},"http://blogbasics.com/examples-of-blogs/#comment-26672":{"rels":["nofollow"],"text":"Reply"},"http://blogbasics.com/examples-of-blogs/#comment-270":{"rels":["nofollow"],"text":"Reply"},"http://blogbasics.com/examples-of-blogs/#comment-3036":{"rels":["nofollow"],"text":"Reply"},"http://blogbasics.com/examples-of-blogs/#comment-5682":{"rels":["nofollow"],"text":"Reply"},"http://blogbasics.com/examples-of-blogs/#comment-6877":{"rels":["nofollow"],"text":"Reply"},"http://blogbasics.com/examples-of-blogs/#comment-736":{"rels":["nofollow"],"text":"Reply"},"http://blogbasics.com/examples-of-blogs/#comment-8615":{"rels":["nofollow"],"text":"Reply"},"http://blogbasics.com/examples-of-blogs/#comment-8684":{"rels":["nofollow"],"text":"Reply"},"http://blogbasics.com/examples-of-blogs/#respond":{"rels":["nofollow"],"text":"Cancel reply"},"http://blogbasics.com/wp-content/plugins/OptinSkin/skins/1/style.css?ver=4.3":{"media":"all","rels":["stylesheet"],"type":"text/css"},"http://blogbasics.com/wp-content/themes/tru/includes/lib/spyr_slidingshare/style.css?ver=0.9.3":{"media":"all","rels":["stylesheet"],"type":"text/css"},"http://blogbasics.com/wp-content/themes/tru/style.css?v=1427736009&ver=2.1.3":{"media":"all","rels":["stylesheet"],"type":"text/css"},"http://blogbasics.com/wp-content/uploads/apple-touch-icon-114x114.png":{"rels":["apple-touch-icon-precomposed"]},"http://blogbasics.com/wp-content/uploads/apple-touch-icon-144x144.png":{"rels":["apple-touch-icon-precomposed"]},"http://blogbasics.com/wp-content/uploads/apple-touch-icon-57x57.png":{"rels":["apple-touch-icon-precomposed"]},"http://blogbasics.com/wp-content/uploads/apple-touch-icon-72x72.png":{"rels":["apple-touch-icon-precomposed"]},"http://blogbasics.com/wp-content/uploads/cropped-Blog-Basics-favicon.png":{"rels":["Shortcut","Icon"],"type":"image/x-icon"},"http://ckckarate.com":{"rels":["external","nofollow"],"text":"Ed JP"},"http://fonts.googleapis.com/css?family=Open+Sans%3A300%2C400italic%2C400%2C600%2C700%7CRokkitt&ver=1.5":{"media":"all","rels":["stylesheet"],"type":"text/css"},"http://jin6000.tumblr.com/":{"rels":["external","nofollow"],"text":"Edward Carty"},"http://optinskin.com/src-4/min/normalize.min.css?ver=4.3":{"media":"all","rels":["stylesheet"],"type":"text/css"},"http://www.blogbasics.com":{"rels":["nofollow"],"text":"Blog Basics"},"http://www.blogbasics.com/contact/":{"rels":["nofollow"],"text":"Contact"},"http://www.blogbasics.com/privacy":{"rels":["nofollow"],"text":"Privacy Policy"},"http://www.blogbasics.com/terms-conditions/":{"rels":["nofollow"],"text":"Terms and Conditions"},"http://www.ferrypress.com/profile.php?u=Herman1879":{"rels":["external","nofollow"],"text":"hgh xl"},"http://www.kuldipsonsjewellers.com/Earring.html":{"rels":["external","nofollow"],"text":"Jewellery Shop in Ranchi"},"https://curlcentric.leadpages.net/leadbox/14581e773f72a2%3A12e927026b46dc/5758142528880640/":{"rels":["nofollow"],"text":"(Click Here)"},"https://www.google.com/+Blogbasics":{"rels":["publisher"]}}
Actually I need output in this form, not in json format. I need data content like this. I found this using JavaScript Microdata Parser from http://foolip.org/microdatajs/live/ but I need same kind of parser in java. Please suggest me. Thanks
"type": [ "http://schema.org/WebPage" ], "properties": { "mainContentOfPage": [ { "type": [ "http://schema.org/Blog" ], "properties": { "blogPost": [ { "type": [ "http://schema.org/BlogPosting" ], "properties": { "headline": [ "Examples of Blogs" ], "author": [ { "type": [ "http://schema.org/Person" ], "properties": { "name": [ "Kenneth Byrd" ] } } ],
Read more: http://foolip.org/microdatajs/live/#ixzz3lJJII7g0
Please have a look at the following.
import java.io.BufferedReader;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONML;
import org.json.JSONTokener;
import org.json.XML;
import com.amazonaws.auth.ClasspathPropertiesFileCredentialsProvider;
import com.amazonaws.regions.Region;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.model.GetObjectRequest;
import com.amazonaws.services.s3.model.S3Object;
public class JsonToXML
{
private AmazonS3Client s3;
public JsonToXML(String inputBucket, String inputFile) throws IOException, JSONException
{
//Connection to S3
s3 = new AmazonS3Client(new ClasspathPropertiesFileCredentialsProvider());
Region usWest2 = Region.getRegion(Regions.US_EAST_1);
s3.setRegion(usWest2);
//Downloading the Object
System.out.println("Downloading Object");
S3Object s3Object = s3.getObject(new GetObjectRequest(inputBucket, inputFile));
System.out.println("Content-Type: " + s3Object.getObjectMetadata().getContentType());
//Read the JSON File
BufferedReader reader = new BufferedReader(new InputStreamReader(s3Object.getObjectContent()));
StringBuffer strBuffer = new StringBuffer("");
int i=0;
while (true) {
String line = reader.readLine();
if (line == null) break;
System.out.println("Running: "+i);
strBuffer.append(line);
i++;
}
JSONTokener jTokener = new JSONTokener(strBuffer.toString());
JSONArray jsonArray = new JSONArray(jTokener);
//Convert to XML
String xml = XML.toString(jsonArray);
File f = new File("XML.xml");
FileWriter fw = new FileWriter(f);
fw.write(xml);
}
}
This is how the Json files look like
[
{
"_type": "ArticleItem",
"body": "Who's signing",
"source": "money.cnn.com",
"last_crawl_date": "2014-01-14",
"url": "http: //money.cnn.com/"
},
{
"_type": "ArticleItem",
"body": "GMreveals",
"title": "GMreveals625-horsepowerCorvetteZ06-Jan.13",
"source": "money.cnn.com",
"last_crawl_date": "2014-01-14",
"url": "http: //money.cnn.com"
}
]
This code generated invalid XML or files without any text. Invalid means, after the last <> it still generate some text, so the entire file is invalid. What is wrong here?
UPDATE
According to the answer of jtahlborn I managed to generate an XML file with the following output.
<array><body>Who's signing</body><_type>ArticleItem</_type><source>money.cnn.com</source><last_crawl_date>2014-01-14</last_crawl_date><url>http: //money.cnn.com/</url></array><array><body>GMreveals</body><_type>ArticleItem</_type><title>GMreveals625-horsepowerCorvetteZ06-Jan.13</title><source>money.cnn.com</source><last_crawl_date>2014-01-14</last_crawl_date><url>http: //money.cnn.com</url></array>
But XML Validator in here says:
XML Parsing Error: junk after document element
Location: http://www.w3schools.com/xml/xml_validator.asp
Line Number 1, Column 181:
You need to flush()/close() the FileWriter to ensure all the data is written to the file.
The problem is that you have 2 "top-level" elements in your xml result (2 "array" elements). xml can only have one top-level element.
UPDATE:
Try this for converting the json to xml:
String xml = XML.toString(jsonArray, "doc");