0

How would i go about making multiple JSON arrays from 1 JSON array?

Basically i have an array filled with JSON objects, but i would like to create multiple arrays with each array being filled with specific JSON objects from the initial array depending on a certain property like ID that every JSON object posesses.

I work in Unity3D with C#.

Anyone any ideas?

[EDIT]

this is 1 object:

{"ID":175355,"Datetime":1523612270,"Module":"Krol 42","Latitude":52.08618,"Longitude":5.11126166666667,"Speed":0}

There are 50 different object with individual IDs in the array but every ID has a 100 instances of it with different lat/lon coordinates

so what i would like is to have an array filled with 50 arrays, so each unique ID has its own array with all the 100 different instances of it in it.

if this makes any sense, i dont know if im explaining it clearly enough, sorry about that.

9
  • In what form are your JSON objects? dynamic? Commented Apr 13, 2018 at 11:36
  • what did you try so far? (stackoverflow.com/help/mcve) Commented Apr 13, 2018 at 11:39
  • 1
    Personally I'd probably deserialise the source json array, use linq queries and .ToArray() to generate the new arrays based on whatever criteria I required, and then serialise back to json. Without knowing more about the objects involved and the expected outcome etc, it's somewhat hard to say though. Commented Apr 13, 2018 at 11:40
  • please edit your question and add sample json and expected result Commented Apr 13, 2018 at 11:40
  • @Efrain they do change, yes. Commented Apr 13, 2018 at 11:57

1 Answer 1

4

Generate a class to hold the JSON data:

public class ModuleInfo
{
    public int ID { get; set; }
    public int Datetime { get; set; }
    public string Module { get; set; }
    public double Latitude { get; set; }
    public double Longitude { get; set; }
    public double Speed { get; set; }
}

Then deserialize the JSON array:

var moduleInfo = JsonConvert.DeserializeObject<List<ModuleInfo>>(jsonString);

Then group by Id using Linq:

var groupedModuleInfo = moduleInfo.GroupBy(m => m.ID).ToArray();

Then you can serialize that array again:

var groupedJson = JsonConvert.SerializeObject(groupedModuleInfo);

This will yield an array of arrays, where each inner array contains all records for one ID:

[[{
        "ID": 60034,
        "Datetime": 1519029071,
        "Module": "Krol 42",
        "Latitude": 51.8423083333333,
        "Longitude": 4.57711,
        "Speed": 0.59264
    }
], [{
        "ID": 58961,
        "Datetime": 1519025476,
        "Module": "Krol 42",
        "Latitude": 51.8422666666667,
        "Longitude": 4.576865,
        "Speed": 0.59264
    }
]]
Sign up to request clarification or add additional context in comments.

1 Comment

Awesome! Thank you @CodeCaster :D

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.