0
dim json2=Newtonsoft.Json.Linq.JObject.Parse("[{""currency_code"":""1ST"",""cash"":""0"",""reserved"":""0""},{""currency_code"":""8BT"",""cash"":""0"",""reserved"":""0""}]")

The doublequotes are just escape characters. The actual string is

[{"currency_code":"1ST","cash":"0","reserved":"0"},{"currency_code":"8BT","cash":"0","reserved":"0"}]

Which as you can see is a legitimate json. Basically it looks like a legitimate json array. I want to turn that into an array of strings

Basically I want to turn that into

{
"{""currency_code"":""1ST"",""cash"":""0"",""reserved"":""0""}",
"{""currency_code"":""8BT"",""cash"":""0"",""reserved"":""0""}"
}

First I parse that into a jobject andd............ I failed.

It's a legitimate json. Why I can't parse that into a jobject?

Some background.

I created 2 json helper function to help me parse any json. One convert json to dictionary. Another parse json into array. In fact, the whole json, is either dictionary (nested or not nested) or array (nested or not nested). Am I correct with this one?

Now the codes are:

Public Shared Function jObjectToDictionary(json As String) As Generic.Dictionary(Of String, String)
    Dim json1 = JObject.Parse(json)
    Dim dict = json1.ToObject(Of Generic.Dictionary(Of String, Object))
    Dim dict2 = dict.ToDictionary(Function(x) x.Key, Function(x) x.Value.ToString)
    Return dict2
End Function

Public Shared Function jObjectToArray(json As String) As Generic.List(Of String)
    Dim json2 = JObject.Parse(json)
    Dim ar = json2.ToObject(Of Generic.List(Of Object))
    Dim ar2 = ar.ConvertAll(Function(x) x.ToString)
    Return ar2
End Function

The code sort of works.

I then did

    Dim jsonar = jsonHelper.jObjectToDictionary(_jsonResult)(starttoken) 'works
    Dim ar1 = jsonHelper.jObjectToArray(jsonar) 'doesn't work

Then I examine why jObjectToArray doesn't work and it leads to this one line code that I think should work but doesn't.

That's what I ask. If you can fix this problem of that one line code, I can figure the rest out.

user4951
  • 32,206
  • 53
  • 172
  • 282

1 Answers1

1

The reason that JObject.Parse is failing is because your JSON represents an array of objects, not just a single object. You can tell because the JSON begins and ends with square brackets [ and ], as opposed to curly braces { and } which denote a single object. To parse an array, you need to use JArray.Parse. (Note you can also use JToken.Parse -- that will parse either a single object or an array.)

Dim json2 = Newtonsoft.Json.Linq.JArray.Parse("[{""currency_code"":""1ST"",""cash"":""0"",""reserved"":""0""},{""currency_code"":""8BT"",""cash"":""0"",""reserved"":""0""}]")

Demo fiddle: https://dotnetfiddle.net/hZlc3m

Brian Rogers
  • 125,747
  • 31
  • 299
  • 300