I am trying to read this JSON code
{
"metadata": {
"clientTransactionId": "",
"serverTransactionId": "20160621101521362-domainrobot-demo.routing-18997-0"
},
"responses": [
{
"domainName": "test.la",
"domainNameUnicode": "test.la",
"domainSuffix": "la",
"earlyAccessStart": null,
"extension": "la",
"generalAvailabilityStart": "2000-01-01T00:00:00Z",
"landrushStart": null,
"launchPhase": "generalAvailability",
"registrarTag": null,
"status": "registered",
"sunriseStart": null,
"transferMethod": "authInfo"
}
],
"status": "success",
"warnings": []
}
With my Java Program:
import javax.json.*;
import java.nio.charset.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.io.*;
public class Main {
public static String readFile(String path, Charset encoding) throws IOException
{
byte[] encoded = Files.readAllBytes(Paths.get(path));
return new String(encoded, encoding);
}
public static void main(String[] args) throws IOException {
String jsonData = readFile("/home/maltepraktikant/workspace/DomainCreator/bin/JsonData.txt", StandardCharsets.UTF_8);
JsonReader jsonreader = Json.createReader(new StringReader(jsonData));
JsonObject object = jsonreader.readObject();
System.out.println(object);
jsonreader.close();
}
}
I have tried different things, but I haven't found a solution yet. It just gives me the error:
Exception in thread "main" javax.json.stream.JsonParsingException: Unexpected char 65.279 at (line no=1, column no=1, offset=0)
at org.glassfish.json.JsonTokenizer.unexpectedChar(JsonTokenizer.java:532)
at org.glassfish.json.JsonTokenizer.nextToken(JsonTokenizer.java:415)
at org.glassfish.json.JsonParserImpl$NoneContext.getNextEvent(JsonParserImpl.java:222)
at org.glassfish.json.JsonParserImpl$StateIterator.next(JsonParserImpl.java:172)
at org.glassfish.json.JsonParserImpl.next(JsonParserImpl.java:149)
at org.glassfish.json.JsonReaderImpl.readObject(JsonReaderImpl.java:101)
at Main.main(Main.java:19)
Has anyone some ideas?
Get the json response and replace all new lines first before parsing it to object.
response.replaceAll("\r?\n", "");
Sample code using GSON API
String json = "{\"msg\" : \"Hello \n World\"}";
System.out.println(json);
json = json.replaceAll("\r?\n", "");
Map<String, String> map = new Gson().fromJson(json, new TypeToken<Map<String, String>>(){}.getType());
System.out.println("Actual message:" + map.get("msg"));
Output:
{"msg" : " Hello
World"}
Actual message: Hello World
In my case error was due to missing quotes for values or key. In the json string null values are not in quotes (ex: "earlyAccessStart": null). Keeping them in quotes would solve the issue.
Note: Validate the json string once through a valitor like
Related
This question already has answers here:
How to parse JSON in Java
(36 answers)
Closed 4 years ago.
I am parsing a json file using json parser object. I am not able to access the request structure and it's inner body content.
I've written code like:
private static final String filePath = "D:\\score_api.json";
public static void main(String[] args) throws FileNotFoundException, IOException, ParseException {
FileReader reader = new FileReader(filePath);
JSONParser jsonParser = new JSONParser();
JSONObject jsonObject = (JSONObject) jsonParser.parse(reader);
System.out.println("++++++++++++++++++\n"+jsonObject);
// prints the whole json content. success!
JSONObject structure = (JSONObject) jsonObject.get("provider");
System.out.println("provider name: " + structure.get("name"));
// prints the provider name. success!
JSONArray req= (JSONArray) jsonObject.get("interactions");
Iterator i = req.iterator();
while (i.hasNext()) {
JSONObject reqObj = (JSONObject) i.next();
System.out.println("description: " + reqObj.get("description") +"\n");
System.out.println("request body: " + reqObj.get("request")); // prints full request body
System.out.println("path: " + reqObj.get("path") +"\n"); // Failing, getting null value.
System.out.println("reponse body: " + reqObj.get("response") +"\n"); // Success
}
}
And it's output:
++++++++++++++++++
{"full json file content prints"}
provider name: SIS
description: API POST Score
request body: {"full request body prints"}
path: null
reponse body: {"status":200}
I am struggling to access request body content. And its child part.
I want to access the value of 'path' and other inner values like 'adptPolVal', 'eEcoId' and Source structure.
I am a newbie to java, m trying but failing.
Any help would appreciated !
Thanks in advance !
Here's my json file content...
{
"consumer": {
"name": "Consumer1"
},
"provider": {
"name": "provider_a"
},
"interactions": [
{
"description": "API Score",
"providerStates": [
{
"name": "",
"params": {}
}
],
"request": {
"method": "post",
"path": "Z123MI6/services/score",
"headers": {
"content-type": "application/json"
},
"body": {
"adptPolVal": true,
"datapoints": [
{
"dataId": " data.point.id ",
"source": {
"srcType": "sourceType.dev.admin",
"snum": "12345",
"instId": "intance id",
"contId": "container id",
"appId": "com.consumer."
},
"userId": "userId",
"ts": 1234567891011,
"lt": 11.12345,
"lng": 123.456,
"ipId": "192.168.1.1",
"geoGraph": ""
}
],
"eEcoId": "ecoId"
}
},
"response": {
"status": 200
}
}
]
}
Try replacing this line
JSONArray req= (JSONArray) jsonObject.get("interactions");
With :
JSONArray req= (JSONArray)jsonObject.getJSONArray("interactions");
You can use following class as a reference to get your desired value.
Please make sure to use getJSONArray() and getJSONObject() method
appropriately according to your output.
package com.test.test;
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import org.codehaus.jettison.json.JSONArray;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;
public class Test {
public static void main(String[] args) throws IOException, JSONException {
String filePath = "C://Users//hello//Desktop//New Text Document.txt";
String string = FileUtils.readFileToString(new File(filePath));
JSONObject jsonObject = new JSONObject(string);
JSONArray jsonArray = jsonObject.getJSONArray("interactions");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject reqObj = jsonArray.getJSONObject(i);
System.out.println("description: " + reqObj.get("description") +"\n");
System.out.println("request body: " + reqObj.get("request")); // prints full request body
System.out.println("reponse body: " + reqObj.get("response") +"\n"); // Success
JSONObject requestBoday = reqObj.getJSONObject("request");
JSONObject body = requestBoday.getJSONObject("body");
}
}
}
I get a JsonObject from another server like this:
{"data": {
"key": "Cooking.Oven.Program.HeatingMode.HotAir",
"options": [
{
"key": "Cooking.Oven.Option.SetpointTemperature",
"value": 230,
"unit": "°C"
},
{
"key": "BSH.Common.Option.Duration",
"value": 1200,
"unit": "seconds"
}
]
}
}
My problem is now. How can I separate this JsonObject in smaller parts.
If this would be a normal object with one key value pair, I would transfere it to a map. But here the line
Map<String, String> map = toMap(this.json);
private Map<String, String> toMap(JsonObject json) {
return new Gson().fromJson(json, new TypeToken<HashMap<String, String>>() {
}.getType());
}
throws an error
Exception occurred while informing handler: java.lang.IllegalStateException: Expected STRING but was BEGIN_ARRAYcom.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected STRING but was BEGIN_ARRAY
What is the easiest solution to get all the entries to a map?
Do you have any hints or cues for me?
Try this:
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
//... get JSON string
String jsonResponse = yourJsonResponseString;
// parse JSON
JSONObject jsonObject = new JSONObject (jsonResponse);
JSONObject data = jsonObject.getJSONObject("data");
String key = data.getString("key");
JSONArray options = data.getJSONArray("options");
for(i=0; i<options.length(); i++){
JSONObject optionsObject = options.getJSONObject(i);
String key = optionsObject.getString("key");
int value = optionsObject.getInt("value");
String unit = optionsObject.getString("unit");
// ... put these values into some object or store it somehow..
}
So, first you have to get values from JSON into String, int etc. Then you can add those values into your custom data structure.
I hope I could help you.
I've got a broblem wih JSON parser.
Here is the JSON response from server.
{
"coord" : {"lon":37.62,"lat":55.75},
"weather":[{"id":803,"main":"Clouds","description":"test","icon":"04d"}],
"base" :"stations",
"main" :{"temp":12.76,"pressure":1007,"humidity":93,"tempmin":12,"tempmax":14},
"visibility":6000,
"wind" :{"speed":4,"deg":300},
"clouds" :{"all":75},
"dt":1504881000,
"sys" :{"type":1,"id":7325,"message":0.0064,"country":"RU","sunrise":1504838942,"sunset":1504886617},
"id" :524901,
"name" :"City",
"cod" :200
}
And java code ....
import org.json.JSONException;
import org.json.JSONObject;
import com.google.gson.*;
public static void main(String[] args) throws JSONException {
try {
JsonParser parser = new JsonParser();
JsonObject json = parser.parse("JSON responce here").getAsJsonObject();
JsonArray weather = json.get("weather").getAsJsonArray(); //no problem
int visibility = json.get("visibility").getAsInt();
int id = json.get("id").getAsInt();
int dt = json.get("dt").getAsInt();
String name = json.get("name").getAsString();
JsonArray clouds = json.get("clouds").getAsJsonArray(); //here is the problem
JsonArray main = json.get("main").getAsJsonArray(); //here is the problem
} catch (Exception e) {
e.printStackTrace();
}
}
The problem is ... when I compile I've got java.lang.IllegalStateException: This is not a JSON Array. on JsonArray clouds = json.get("clouds").getAsJsonArray(); and others lines like this.
BUT JsonArray weather = json.get("weather").getAsJsonArray(); is OK...
I don't understand what is happening... but the array "weather" node has no problem... totally. Please, help me... what's wrong?
Because it is a Json Object
JsonObject json = json.get("clouds").getAsJsonObject()
It will work...
Or you can change the data as given below
{
"coord" : {"lon":37.62,"lat":55.75},
"weather":{"id":803,"main":"Clouds","description":"test","icon":"04d"},
"base" :"stations",
"main" :{"temp":12.76,"pressure":1007,"humidity":93,"tempmin":12,"tempmax":14},
"visibility":6000,
"wind" :{"speed":4,"deg":300},
"clouds" :[{"all":75}],
"dt":1504881000,
"sys" :{"type":1,"id":7325,"message":0.0064,"country":"RU","sunrise":1504838942,"sunset":1504886617},
"id" :524901,
"name" :"City",
"cod" :200
}
I need to pull out value of RecordOne from following JSON.
{
"errors": [],
"data": {
"paging": {
"RecordOne": 8,
"RecordTwo": 9,
"recordThree": 2,
"totalNumberOfRecords": 86052
},
"products": [
{
"testabstract": "test data",
"authors": "Frank Jr.",
"invertedauthors": "Frank VJr.",
"formatCode": "KND"
}
]
}
}
I'm using Java as language and JSON object to achieve the same, following is what I'm using:
protected String getTokenValueUnderHeirarchy(String responseString){
JSONObject json = new JSONObject(responseString);
String val= json.getJSONObject("data").getJSONObject("paging").getString("RecordOne");
System.out.println("val::"+val);
return val;
}
I'm getting value of val = 1, it should be 8
If I try to seek value for key totalNumberOfRecords with same code it returns correct value which is 86052
I know it's something silly but I can't catch it.
When I ran your code with the JSON example, I ended up with a "JSONException: JsonObject["RecordOne"] is not a string"..... which it isn't. Wrapping the 8 with double quotes: "8" returned the value that you expected. You can access this value with other get methods: getInt if you would like.
This test case parses both a String and an int. I pulled this from your example. Does it run for you?
package org.nadnavillus.test;
import org.json.JSONObject;
import org.junit.Test;
public class TestCase {
protected String getTokenValueUnderHeirarchy(String responseString) throws Exception {
JSONObject json = new JSONObject(responseString);
String val= json.getJSONObject("data").getJSONObject("paging").getString("RecordOne");
System.out.println("val::"+val);
return val;
}
protected String getTokenValueUnderHeirarchyInt(String responseString) throws Exception {
JSONObject json = new JSONObject(responseString);
int val= json.getJSONObject("data").getJSONObject("paging").getInt("RecordTwo");
System.out.println("val::"+val);
return String.valueOf(val);
}
#Test
public void testJson() throws Exception {
String input = "{\"errors\": [], \"data\": {\"paging\": {\"RecordOne\": \"8\", \"RecordTwo\": 9, \"recordThree\": 2, \"totalNumberOfRecords\": 86052}}}";
String test = this.getTokenValueUnderHeirarchy(input);
System.out.println(test);
test = this.getTokenValueUnderHeirarchyInt(input);
System.out.println(test);
}
}
I am new to Java,and using below code to parse JSON,but I am getting java.lang.NullPointerException error when the offers {} node is coming with empty values ,which is public class in my code.
How to handle empty JSON nodes/keys ??
The code is able to parse JSON if there is data under "offers" like "info",but exiting with NULL exception error when JSON returns and empty as shown below.
ERROR MSG :
Exception in thread "api_temp_1.dat" java.lang.NullPointerException
at com.t.dw.dl.api.data.Pkg_Data.getCount(Pkg_Data.java:57)
at com.t.dw.dl.api.DataRetrieveRunnable.run(DataRetrieveRunnable.java:185)
Code extracts from error lines shown
public long getCount() {
if (offers != null)
return offers.getPkg().size();
return 0;
}
**Code from com.t.dw.dl.api.DataRetrieveRunnable.run(DataRetrieveRunnable.java:185)**
try
{
Pkg_Data dls = parseResult(result);
if (dls.getCount() > 0)
{
fw.write(deals.writeResults(fields, delimiter));
threadStats.increment(Stats2.COUNT_OF_ROWS_PROCESSED,
dls.getCount());
}
}
Parsing code:
private Pkg_Data parseResult( String result ) throws JsonParseException {
JsonParser parser = new JsonParser();
JsonElement jo = parser.parse(result);
Gson gson = new Gson();
Pkg_Data ehw = gson.fromJson(jo, Pkg_Data.class);
return ehw;
}
CODE:
import java.util.ArrayList;
public class offers
{
private ArrayList<PkgData> pkg;
class Pkgdata
{
Info Info;
class Info
{
String Id;
String Url;
}
public String getId() {
if (Info != null && Info.Id != null)
return Info.Id;
return "";
}
SAMPLE JSON: NOT working for this where "offers" returns empty
{
"offerInfo":{
"siteID":"1",
"language":"en_US",
"currency":"USD"
},
"offers":{ }
}
That is because offer is compared to the Class that you giving to refer so in that case Json will be wrong try with this Json it will work.
{
"offerInfo": {
"siteID": "1",
"language": "en_US",
"currency": "USD"
},
"offers": {
"siteID": " ",
"language": "",
"currency": " "
}
}
Because Compiler not able to find any field attribute in side your offer object so its giving error.
try this Json.