Hey all I am having difficultys in making this string JSON that I have into an object so that I can use it like this:
json("go")("to")("needed")("spot").toString
and get my value.
Currently the XML to JSON looks like this:
{
"?xml": {
"#version": "1.0",
"#encoding": "UTF-8"
},
"data": {
"recordCount": "1",
"metadata": {
"elementType": [
{
"name": "F_Paragraphtext",
"uiType": "textArea",
"dataType": "string",
"label": "Text String",
"dataLabel": ""
}
]
},
"records": {
"F_Form1": {
"#application_uid": "2a667c59-225c-4954-8e04-77bb083e5180",
"#uid": "61f876f4-9760-4013-85bb-37965cff1fb6",
"F_SingleLine": "test",
"F_Paragraphtext": "{\"Data\":{\"DevisionName\":\"testing service after added field\",\"DevisionCode\":\"test\",\"CodeInString\":\"test^test|4/15/2015|50%|test^test|4/15/2015|25%|test^test|4/23/2015|50%~test^test|4/23/2015|N/A|test^test|4/8/2015|N/A|test^test|3/31/2015|N/A~test^test|4/10/2015|N/A|test^test|5/1/2015|50%|test^test|4/18/2015|N/A~test^test|3/30/2015|50%|test^test|4/24/2015|50%|test^test|5/9/2015|100%~test^test|3/30/2015|25%|test^test|3/30/2015|100%|test^test|4/11/2015|75%\"}}"
}
}
}
}
And I am trying to get the value for F_Paragraphtext, #application_uid & #uid.
The VB.net code I have:
Dim doc1 As XmlDocument = New XmlDocument()
doc.LoadXml(serverResponse)
Dim json1 As String = Newtonsoft.Json.JsonConvert.SerializeXmlNode(doc, Newtonsoft.Json.Formatting.Indented)
jsreader = New Newtonsoft.Json.JsonTextReader(New StringReader(json1))
Try
json = DirectCast(New Newtonsoft.Json.JsonSerializer().Deserialize(jsreader), Newtonsoft.Json.Linq.JObject)
Catch ex As Exception
MsgBox(ex.Message)
End Try
For Each Row In json("data")("records")(febFormID)
Try
dName = json("#application_uid").ToString
Catch ex As Exception
MsgBox(ex.Message)
End Try
Next
While Row value is:
{"#application_uid": "2a667c59-225c-4954-8e04-77bb083e5180"}
The error falls on the dName = Row("#application_uid").ToString. The error is Object reference not set to an instance of an object..
Not quite sure what all I am missing in order to be able to retrieve the Row values but apparently its something....
...making this string JSON that I have into an object so that I can use it like this:
json("go")("to")("needed")("spot").toString
I am trying to get the value for F_Paragraphtext, #application_uid & #uid.
Dim jstr As String = File.ReadAllText(filename)
Dim myJ = JObject.Parse(jstr)
Console.WriteLine("{0} == {1}", "F_Paragraphtext",
myJ("data")("records")("F_Form1")("F_Paragraphtext"))
Console.WriteLine("{0} == {1}", "#application_uid",
myJ("data")("records")("F_Form1")("#application_uid"))
Console.WriteLine("{0} == {1}", "#uid",
myJ("data")("records")("F_Form1")("#uid"))
Output:
F_Paragraphtext == {"Data":{"DevisionName":"testing service after added field","DevisionCode":"test","CodeInString":"test^test|4/15/2015|50%|test^test|4/15/2015|25%|test^test|4/23/2015|50%~test^test|4/23/2015|N/A|test^test|4/8/2015|N/A|test^test|3/31/2015|N/A~test^test|4/10/2015|N/A|test^test|5/1/2015|50%|test^test|4/18/2015|N/A~test^test|3/30/2015|50%|test^test|4/24/2015|50%|test^test|5/9/2015|100%~test^test|3/30/2015|25%|test^test|3/30/2015|100%|test^test|4/11/2015|75%"}}
#application_uid == 2a667c59-225c-4954-8e04-77bb083e5180
#uid == 61f876f4-9760-4013-85bb-37965cff1fb6
Related
This is the json response format that I have and need to read the first node value "html". I have tried to few ways to get the value but unable to get it
[
{
"html": "<!DOCTYPE html>\n <html>\n <head>\n <\/html>\n \n",
<\/html>\n \n",
"headers": {},
"subject": "Register new account",
"messageId": "475603953.247.1565607800153#dfrsbdd201.abc.com.au",
"priority": "normal",
"from": [],
"to": [],
"date": "2019-08-12T11:03:20.000Z",
"receivedDate": "2019-08-12T11:09:42.000Z",
"receivedAt": "2019-08-12T11:09:44.900Z"
},
{+},
{+}
]
I tried couple of things
RequestSpecification emailReq = given().with().pathParam("email",emailName);
Response emailResp = emailReq.contentType("application/json").get("https://restmail.net/mail/{email}");
JSONObject value = new JSONObject(emailResp.asString());
I got this error
org.json.JSONException: A JSONObject text must begin with '{' at 1 [character 2 line 1]
at org.json.JSONTokener.syntaxError(JSONTokener.java:505)
and then I removed this last line to use But this does not gives me error. pls refer screenshot for this
JSONArray responseJson = new JSONArray(emailResp.asString());
Tried this as well
List<HashMap<String, Object>> jsonObjectsInArray = emailResp.jsonPath().getList("$");
for (HashMap<String, Object> singleLeg : jsonObjectsInArray) {
String value = (String) singleLeg.get("html");
}
But again array size is 0
Need some suggestion of how to get the value of node - "html". Pls suggest. what mistake am I doing here?
Thanks in advance
RequestSpecification emailReq = given().with().pathParam("email",emailName);
int retries = 5;
List<HashMap<String, Object>> emails = Arrays.asList();
. . .
emailResp = emailReq.get("restmail.net/mail{email}");
if (emailResp.getStatusCode() == 200) { emails = emailResp.jsonPath().getList("$");
String email = emails.get(0).get("html").toString();
Hi I asked the similar question before: I have a large JSON file but the information I need is only small part of it. However, that part is a two dimensional array from "text"."size" part.Is any way I can loop each array and and get the number from what I have already?
{"widget": { "debug": "on", "window": { "title": "Sample Konfabulator Widget", "name": "main_window", "width": 500, "height": 500 }, "image": { "src": "Images/Sun.png", "name": "sun1", "hOffset": 250, "vOffset": 250, "alignment": "center" }, "text": { "data": "Click Here", "size": [[0,1,2,3,4],[5,6,7,8,9],[10,11,12,13,14]], "style": "bold", "name": "text1", "hOffset": 250, "vOffset": 100, "alignment": "center", "onMouseUp": "sun1.opacity = (sun1.opacity / 100) * 90;" } } }
I was taught from someone(thank you!) to use the following code
Option Explicit
Public Sub GetInfo()
Dim strJSON As String, json As Object, rowNumber As Long
Application.ScreenUpdating = False
Const PATH As String = "C:\Users\User\Desktop\test.JSON"
strJSON = GetJSONFromFile(PATH)
Set json = JsonConverter.ParseJson(strJSON)
Set json = json("widget")("text")
Dim key As Variant
With ThisWorkbook.Worksheets("Sheet1")
For Each key In json
rowNumber = rowNumber + 1
.Cells(rowNumber, 1) = key
.Cells(rowNumber, 2) = json(key)
Next key
End With
Application.ScreenUpdating = True
End Sub
Many Thanks
Seeing expected output would help. If you are simply after the items within the collection of collections returned by JsonConverter.ParseJson(strJSON)("widget")("text")("size") then the following will empty them.
Option Explicit
Public Sub GetInfo()
Dim strJSON As String, json As Object, rowNumber As Long, i As Long, j As Long
Const PATH As String = "C:\Users\User\Desktop\test.JSON"
strJSON = GetJSONFromFile(PATH)
Set json = JsonConverter.ParseJson(strJSON)("widget")("text")("size") '<collection of collections
With ThisWorkbook.Worksheets("Sheet1")
For i = 1 To json.Count
For j = 1 To json(i).Count
rowNumber = rowNumber + 1
.Cells(rowNumber, 1) = json(i)(j)
Next
Next
End With
End Sub
Public Function GetJSONFromFile(ByVal PATH As String) As String
Dim fso As Object, f As Object, outputString As String
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.OpenTextFile(PATH)
Do Until f.AtEndOfStream
outputString = f.ReadAll()
Loop
f.Close
GetJSONFromFile = outputString
End Function
JSON structure:
You can see the path down to the collection of collections in the JSON structure below. The {} are dictionaries and the [] are collections.
I receive a JSon string from WS. It's so long that I can't use Json2charp to parse it and receive the structurated class.
I want to parse the string with a command. How is it possible?
I don't know the classes so I can't use a command like:
Dim result = JsonConvert.DeserializeObject(Of MyClass.RootObject)(String_From_File)
Is it possible from the string to obtain the class without using json2charp site ?
For example, in vs.net if on the variable 'string_from_file' I choose 'Json Visualizer' and see all classes and data in correct mode.
How can I obtain the same in my code ?
I have installed Newtonsoft.json
If you cannot use the json to class mappers like NewtonSoft.Json. You can use the Windows.Data.Json api. It let you parse and extract the data you want from your JSON string.
JsonValue jsonValue = JsonValue.Parse("{\"Width\": 800, \"Height\": 600, \"Title\": \"View from 15th Floor\", \"IDs\": [116, 943, 234, 38793]}");
double width = jsonValue.GetObject().GetNamedNumber("Width");
double height = jsonValue.GetObject().GetNamedNumber("Height");
string title = jsonValue.GetObject().GetNamedString("Title");
JsonArray ids = jsonValue.GetObject().GetNamedArray("IDs");
You can find a sample in the Windows Universal Sample GitHub.
A complex object parsing is shown here. I've extracted the most relevant parts here. The JSON string is provided to the User constructor which is extracting what it needs and then delegating the parsing to the nested School constructor.
{
"id": "1146217767",
"phone": null,
"name": "Satya Nadella",
"education": [
{
"school": {
"id": "204165836287254",
"name": "Contoso High School"
},
"type": "High School"
},
{
"school": {
"id": "116138758396662",
"name": "Contoso University"
},
"type": "College"
}
],
"timezone": -8,
"verified": true
}
This JSON fragment is parsed with this code:
public User(string jsonString) : this()
{
JsonObject jsonObject = JsonObject.Parse(jsonString);
Id = jsonObject.GetNamedString(idKey, "");
IJsonValue phoneJsonValue = jsonObject.GetNamedValue(phoneKey);
if (phoneJsonValue.ValueType == JsonValueType.Null)
{
Phone = null;
}
else
{
Phone = phoneJsonValue.GetString();
}
Name = jsonObject.GetNamedString(nameKey, "");
Timezone = jsonObject.GetNamedNumber(timezoneKey, 0);
Verified = jsonObject.GetNamedBoolean(verifiedKey, false);
foreach (IJsonValue jsonValue in jsonObject.GetNamedArray(educationKey, new JsonArray()))
{
if (jsonValue.ValueType == JsonValueType.Object)
{
Education.Add(new School(jsonValue.GetObject()));
}
}
}
public School(JsonObject jsonObject)
{
JsonObject schoolObject = jsonObject.GetNamedObject(schoolKey, null);
if (schoolObject != null)
{
Id = schoolObject.GetNamedString(idKey, "");
Name = schoolObject.GetNamedString(nameKey, "");
}
Type = jsonObject.GetNamedString(typeKey);
}
If you cannot use the automatic mapping from NewtonSoft.Json, you have no other way than doing it yourself.
Is not so simple.
The Json i received is very complicated and have many class
So i can't use
double width = jsonValue.GetObject().GetNamedNumber("Width");
Inside class i have more ...
I have a document with the following schema,
{
"_index": "test",
"_type": "user",
"_id": "2",
"_score": 1,
"_source": {
"id": 2,
"accountExpired": false,
"accountLocked": false,
"dateCreated": "2016-07-19T03:13:07Z",
"employee": {
"class": "bropen.framework.core.osm.Employee",
"id": 1
}
}
}
I want to modify the value of field "employee"
I have tried this:
String employee="\"{\"class\":\"bropen.framework.core.osm.Employee\",\"id\":1,\"birthdate\":null,\"code\":null,\"dateCreated\":\"2016-07-19T03:13:07Z\",\"degree\":null,\"disabled\":false,\"email\":null,\"entryDate\":null,\"graduateDate\":null,\"groups\":[],\"identities\":[{\"class\":\"bropen.framework.core.osm.EmployeeIdentity\",\"id\":1},{\"class\":\"bropen.framework.core.osm.EmployeeIdentity\",\"id\":33}],\"identityNumber\":null,\"lastUpdated\":\"2016-07-19T07:58:34Z\",\"level\":0.10,\"location\":null,\"mainIdentityId\":1,\"major\":null,\"mobile\":null,\"name\":\"张三\",\"nation\":null,\"nativePlace\":null,\"notes\":null,\"organization\":{\"class\":\"bropen.framework.core.osm.Organization\",\"id\":2},\"payrollPlace\":null,\"professionalRank\":null,\"qualification\":null,\"rank\":null,\"sequence\":10,\"sex\":null,\"syncId\":null,\"telephoneNumber\":null,\"title\":null,\"type\":1,\"user\":{\"class\":\"bropen.framework.core.security.User\",\"id\":2},\"workingDate\":null,\"workingYears\":null}\"";
try {
client.prepareUpdate("test", "user", "2")
.setDoc(jsonBuilder().startObject().field("testfield", employee).endObject()).get();
} catch (IOException e) {
e.printStackTrace();
}
return error info :
java.util.concurrent.ExecutionException: RemoteTransportException[[node-1][192.168.0.224:9300][indices:data/write/update]]; nested: RemoteTransportException[[node-1]
[192.168.0.224:9300][indices:data/write/update[s]]]; nested:
MapperParsingException[object mapping for [employee] tried to parse field [employee] as object, but found a concrete value];
at org.elasticsearch.common.util.concurrent.BaseFuture$Sync.getValue(BaseFuture.java:290)
how to use jsonBuilder() to build a json like this:
employee:{
"id":"1",
"class":"bropen",
"name":"Tom"
}
and modify the value of field "employee"?
--------------update------------------
I tried again:
public static void upMethod1() {
XContentBuilder json;
try {
json = jsonBuilder().startObject("employee").field("id", 1)
.field("class", "bropen").field("name", "Tom").endObject();
UpdateRequest request = new UpdateRequest();
request.index("test");
request.type("user");
request.id("2");
request.doc(json);
client.update(request).get();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
Error info:
java.util.concurrent.ExecutionException: RemoteTransportException[[node-1][127.0.0.1:9300][indices:data/write/update]]; nested: RemoteTransportException[[node-1][192.168.0.87:9300][indices:data/write/update[s]]]; nested: NotSerializableExceptionWrapper[not_x_content_exception: Compressor detection can only be called on some xcontent bytes or compressed xcontent bytes];
at org.elasticsearch.common.util.concurrent.BaseFuture$Sync.getValue(BaseFuture.java:290)
updating document is easy when you use json builder.
in your case inner object name is employee so you have to make object with name as "employee".
below is the code that helps you to understand the use of json builder.
XContentBuilder json = jsonBuilder()
.startObject("employee")
.field("id", 1)
.field("class", "bropen")
.field("name","Tom")
.endObject();
UpdateRequest request = new UpdateRequest();
request.index("test");
request.type("user");
request.id("2");
request.doc(json);
client.update(request).get();
you can see generated json using below code
String output = builder.string();
json = jsonBuilder().startObject()
.startObject("employee")
.field("id", 1)
.field("class", "bropen")
.field("name", "Tom")
.endObject()
.endObject();
UpdateRequest request = new UpdateRequest();
request.index("test");
request.type("user");
request.id("2");
request.doc(json);
System.out.println(json.toString());
client.update(request).get();
Hey all I am getting the following error at random spots in my code:
Object reference not set to an instance of an object.
I know why I am getting it. It does not find the correct property that I have it looking for and therefore it gives the error. Some may have that property and some, as this error shows, may not.
What can I do in order to check first to make sure it has that property? Currently I just have a Try/catch method in place so it can keep going if it does find something that's not there.
For Each Row In json("data")
Try
thePostID = DirectCast(Row("id").ToString(), String)
thePostType = DirectCast(Row("type").ToString(), String)
thePosterID = DirectCast(Row("from")("id").ToString(), String)
thePosterName = DirectCast(Row("from")("name").ToString(), String)
Catch ex As NullReferenceException
msgbox("Did not find that particular property!")
End Try
Next
update
{
"data": [
{
"id": "102zzz533zz_10z52zz9zzzz94z3",
"from": {
"id": "102zzzzz95zzz7",
"name": "Jim zzzzz"
},
"likes": {
"data": [
{
"id": "85zzzzz35zzzz0",
"name": "Anna zzzzz"
},
{
"id": "10zzzz93z31zzzzz",
"name": "Vanessa zzzz zzzz"
},
{
"id": "1zzz44zzz48731z6",
"name": "Leta zzzzzz"
}
],
"paging": {
"cursors": {
"after": "MTAyMdfasdfwrtMTkyNg=",
"before": "ODUasdfasrU5Mwerw"
}
}
}
etc...
This JSON above follows in the same data path as all the others.
Using #Andrews code below:
thePostLikes = NullSafeSelect(Row, "likes.data.id")
If thePostLikes <> "NA" Then
For Each Row2 In json("likes")("data")
thePostLikesID += NullSafeSelect(Row2, "id") & ","
thePostLikesName += NullSafeSelect(Row2, "name") & ","
Next
End If
The value of thePostLikes is always Nothing
There may be a more graceful way to do this that's built in to JSON.NET, but here's a helper function that will just return Nothing if the path you supply doesn't exist:
Function NullSafeSelect(ByVal obj As JToken, ByVal path As String) As String
Dim result As String = Nothing
Dim value As JToken = obj.SelectToken(path, False)
if (value IsNot Nothing)
result = value.ToString()
End If
Return value
End Function
You would call it from your loop like this:
For Each row in json("data")
Dim thePostID As String = NullSafeSelect(row, "id")
Dim thePostType As String = NullSafeSelect(row, "type")
Dim thePosterId As String = NullSafeSelect(row, "from.id")
' ... etc
Next
Note that you do not need the DirectCast because the return type of the function is already String.