org.json.JSONException: Expected literal value at character 85 - json

This is my json string :
{
gateway=vary,
gateway_text=xyz,
gateway_data=,
start=17/02/2022 06:23:45,
end=17/03/2022 06:23:45,
promo_time=17/03/2022 06:23:45,
in_process_canceled=0.0,
id=817957632
}
When I am trying to convert it to JSON object, it is throwing the exception
val obj = JSONObject(purchaseData.toString())
Please help me resolve this.

Your json is not a valid json, remove "=" and put double quotes in property and values
{
"gateway": "vary",
"gateway_text": "xyz",
"gateway_data": "ss",
"start": "17/02/202206:23:45",
"end": "17/03/202206:23:45",
"promo_time": "17/03/202206:23:45",
"in_process_canceled": "0.0",
"id": "817957632"
}
Then it will work

This can handled by converting it to a json string ;
json = json.replace(" ","")
json = json.replace("\n","")
json = json.replace("{", "{\"")
json = json.replace("}", "\"}")
json = json.replace("=", "\":\"")
json = json.replace(",", "\",\"")
val obj = JSONObject(json)

Related

How convert string to json or map to pair in dart if not valid json

What is the best method to convert string to json in my example or map key value.
var str = "created_at: 2020-07-09T06:32:19Z, entry_id: 9510, field1: null, field2: 19.00"
json.decode(str);
Error:
FormatException: SyntaxError: Unexpected token c in JSON at position 0
To convert Map/String -> JSON we use json.encode()
String str = "This is a String";
//for JSON format
json.encode(str);
Map<string,int> myMap = {"a":1};
//to convert into JSON
json.encode(myMap); // => "{"a":1}" JSON form
Similarly to convert JSON -> Map/String we use json.decode()
While json.decode is the correct method to use, your string is not valid JSON. Your string in valid json would look something like this:
{
"created_at": "2020-07-09T06:32:19Z",
"entry_id": 9510,
"field1": null,
"field2": 19.0
}
If you have a Map that you want to encode to JSON, use json.encode.
If this is your first time working with JSON, you might want to check out a tutorial on the syntax first (maybe this)

Deserializing JSON: The input is not a valid Base-64 string as it contains a non-base 64 character

Problem:
I just can't figure out what's wrong with the JSON below.
Error:
'The input is not a valid Base-64 string as it contains a non-base 64 character, more than two padding characters, or an illegal character among the padding characters.'
Test:
I ran a JSON validation tool on it and it passed as valid JSON. However, I continue to receive a base-64 conversion error.
{
"Courier": {
"CourierId": "e168d837-0f0e-4f61-8a3d-725b53d11277",
"Name": "Jeremy Bot",
"ProfileImage": "undefined_image",
"LastLocation": {
"Latitude": 25.87427,
"Longitude": -80.12173
},
"IsSubscribed": true,
"Timestamp": "2020-04-11T19:11:21.1821483-04:00"
},
"Request": {
"RequestId": "78d31dab-e631-4f95-aa31-d95b218a1850",
"Customer": {
"CustomerId": "some_customer_id",
"Name": "John Doe",
"Location": {
"Latitude": 25.87427,
"Longitude": -80.12173
},
"Phone": "(XXX-XXX-XXXX)"
},
"Carriers": {
"Restaurants": [],
"Stores": []
}
},
"ETA": "30 minutes"
}
Test 2:
I thought that the cause could be a negative number in my JSON.
However, the following didn't work:
let handleNegativeValues = JsonSerializerSettings(FloatParseHandling=FloatParseHandling.Decimal)
let payload = JsonConvert.DeserializeObject<'T>(json, handleNegativeValues)
Cause:
Here's the code that I execute which results in the error:
let payload = JsonConvert.DeserializeObject<'T>(json)
Appendix:
Here's the root type that I'm trying to deserialize to:
[<DataContract>]
type CourierAcceptedSubmission = {
[<field: DataMember(Name="Courier")>]
Courier : Courier
[<field: DataMember(Name="Request")>]
Request : Request
[<field: DataMember(Name="ETA")>]
ETA : string
}
Here's the type that contains ProfileImage:
[<DataContract>]
type Courier = {
[<field: DataMember(Name="CourierId")>]
CourierId : string
[<field: DataMember(Name="Name")>]
Name : string
[<field: DataMember(Name="ProfileImage")>]
ProfileImage : string
[<field: DataMember(Name="LastLocation")>]
LastLocation : Coordinate
[<field: DataMember(Name="IsSubscribed")>]
IsSubscribed : bool
[<field: DataMember(Name="Timestamp")>]
Timestamp : DateTime
}
Json.Net handles byte arrays by automatically converting them to and from base-64 encoded strings. So if you are deserializing JSON into a class that has a property declared as byte[] but the corresponding string value in the JSON is not base-64 encoded, for example "undefined_image", that will cause the error you are seeing.
The easiest fix is to change the type of the offending property from byte[] to string. However, if you have a situation where the JSON will sometimes contain valid base-64 strings and sometimes not, and you do want it to be a byte[] to handle the data for the valid case, you would need to create a custom JsonConverter to handle that property.
Though its bit late but i think someone else may face similar issue, so writing down solution which worked for me.
Convert byte[] of image in string by using ASCIIEncoding:
using System.Text;
...
...
ProfileImage = ASCIIEncoding.Default.GetString(byte_array_of_image);

How to handle data type wise XML to JSON conversion by using NewtonSoft

I am using NewtonSoft namespace to convert the xml data to json. I want the json data value to preserve the data type. But, by using "SerializeXmlNode" it is giving json data value in string.
XML Data is:
<statecode>1</statecode>
<iskit>false</iskit>
<name>PokeMon go</name>
<ExpirationDate>2013-12-31T00:00:00</ExpirationDate>
<price>25.00</price>
I am using the following code:
string requestData = #"<products><statecode>1</statecode>
<iskit>false</iskit>
<name>PokeMon go</name>
<ExpirationDate>2013-12-31T00:00:00</ExpirationDate>
<price>25.00</price></products>";
XmlDocument transformData = new XmlDocument();
transformData.LoadXml(requestData);
foreach(XmlNode data in transformData.GetElementsByTagName("products"))
{
string transformedJsonData = JsonConvert.SerializeXmlNode(data);
}
Output:
{
"statecode" : "1",
"iskit" : "false",
"name":"PokeMon go",
"ExpirationDate":"2013-12-31T00:00:00",
"price":"25.00"
}
Expected Output:
{
"statecode" : 1,
"iskit" : false,
"name":"PokeMon go",
"ExpirationDate":"2013-12-31T00:00:00",
"price": 25.00
}
You can observe output is in string.

Collect All appID's from a JSON file

My question is about a JSON file, of which I'm getting errors when putting certain values in a text component.
{
"response": {
"game_count": 4,
"games": [
{
"appid": 10,
"playtime_forever": 0
},
{
"appid": 20,
"playtime_forever": 0
},
{
"appid": 30,
"playtime_forever": 0
},
{
"appid": 40,
"playtime_forever": 0
}
]
}
}
I'm trying to get the values "10,20,30,40" from "appid" in a RichTextBox, one below the other. For this, I am using this code:
JsonString = file
Dim jsonObject As JObject = JObject.Parse(JsonString)
Dim JsonArray As JArray = JArray.Parse(jsonObject.SelectToken("games").ToString)
For Each item As JObject In JsonArray
RichTextBox2.Text = item.SelectToken("appid").ToString
Next
But I'm getting the following error in line 4 of the above code:
Object reference not set to an instance of an object
Is there a way to fix this? I believe my code is right. I'm using the NewtonSoft library.
You can use SelectTokens("..appid") to recursively descent the JSON token hierarchy and find values of properties named "appid", where ".." is the JSONPath recursive descent operator:
Dim jsonObject As JToken = JToken.Parse(JsonString)
Dim appids = jsonObject _
.SelectTokens("..appid") _
.Select(Function(t) CType(t, Long)) _
.ToList()
After finding all "appid" values I cast then to Long using an explicit conversion cast. You could cast to Int If you are certain that all appid values will be less than Int.MaxValue. Or you could cast then to String if you're not interested in the numeric values.
Working .Net fiddle.

how to handle '\' in json string

In my json message the field which should have one '\' comes with '\\'
In the below example
"validation": "^[^\\s][a-zA-Z\\(\\) ,.-]+[^\\s]$"
Should come as
"validation": "^[^\s][a-zA-Z\(\) ,.-]+[^\s]$",
I am not getting why it is happening like this. Any one out there to help me.
"getTransactionDataRequirementsResponse": {
"return": [
{
"errorMessage": "Cannot start or end with whitespace",
"validation": "^[^\\s][a-zA-Z\\(\\) ,.-]+[^\\s]$",
},
{
"errorMessage": "Cannot start or end with whitespace",
"validation": "^[^\\s][a-zA-Z\\(\\) ,.-]+[^\\s]$",
},
}
No way I could pass an odd number of backslashes through json. Below is one test code
String jsonString = "{\"validation\" : \" 1\\ 2\\\\ 3\\\\\\ 4\\\\\\\\\ 3\\\" }";
JsonParser jsonParser = new JsonParser();
JsonElement jsonElement = jsonParser.parse(jsonString);
JsonObject jsonObject = jsonElement.getAsJsonObject();
System.out.println("validation=" + jsonObject.get("validation"));
Output comes as below
validation=" 1 2\ 3\ 4\\"
When you encode data to JSON format all special chars are escapes (e.g. '/' => '//'). And if you want to use JSON data, decodes them using the parseJSON() method.